【问题标题】:image resize and then rotate in canvas - javascript图像调整大小然后在画布中旋转 - javascript
【发布时间】:2014-11-21 22:33:59
【问题描述】:

我正在使用大小为 1024 x 768 的图像,并且我的画布大小为 300 x 300,因此我想先将图像大小调整为 300 x 300,然后在画布内按比例旋转它。 我正在使用以下代码,但它正在调整图像大小但在画布外旋转一些元素。所以如果你点击右键然后你什么都看不到,然后再次点击右键,你就会看到向下旋转的图像。

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var degrees=0;
var image=document.createElement("img");
image.onload=function(){
    ctx.drawImage(image,0,0,300,300);
}
image.src="http://media1.santabanta.com/full1/Outdoors/Landscapes/landscapes-275a.jpg";
image.width = 300;
image.height = 300;
 $("#clockwise").click(function(){
     degrees+=90
     ctx.clearRect(0,0,canvas.width,canvas.height);
     ctx.save();
     ctx.translate(300,300);
     ctx.rotate(degrees*Math.PI/180);
     ctx.drawImage(image,0,0,300,300);
     ctx.restore();
});

请检查我在 JSFiddle 中的代码 http://jsfiddle.net/6ZsCz/914/

【问题讨论】:

    标签: javascript jquery canvas rotation


    【解决方案1】:

    试试这个变化。

    • 平移到画布的中心。
    • [x,y] 偏移量为 image.width/2 和 image.height/2 的 DrawImage。此偏移量是必需的,因为 translate 有效地使画布中心点 [150,150] 成为新的画布原点 [0,0]。您需要负偏移量来向左和向上拉绘图以补偿新的原点。

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    
    var degrees=0;
    
    var image=document.createElement("img");
    image.onload=function(){
      ctx.drawImage(image,0,0,300,300);
    }
    image.src="http://media1.santabanta.com/full1/Outdoors/Landscapes/landscapes-275a.jpg";
    
    
    $("#clockwise").click(function(){
      degrees+=90
      ctx.clearRect(0,0,canvas.width,canvas.height);
      ctx.save();
      ctx.translate(150,150);
      ctx.rotate(degrees*Math.PI/180);
      ctx.drawImage(image,0,0,image.width,image.height,-150,-150,300,300);
      ctx.restore();
    });
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <canvas id="canvas" width=300 height=300></canvas><br>
    <button id="clockwise">Rotate right</button>

    【讨论】:

      猜你喜欢
      • 2019-07-11
      • 2017-10-19
      • 2014-11-18
      • 1970-01-01
      • 2012-08-27
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 2023-02-25
      相关资源
      最近更新 更多