图像调整大小,然后在画布中旋转 - javascript

时间:2014-09-26 20:12:33

标签: javascript jquery canvas rotation

我正在使用尺寸为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/

1 个答案:

答案 0 :(得分:0)

尝试此变体。

  • 翻译到画布的中心。
  • 具有[x,y]偏移image.width / 2&的DrawImage。 image.height / 2。此偏移是必需的,因为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>

相关问题