我希望允许用户旋转画布,同时在旋转后不再适合更改尺寸,这是一个小提琴:
我似乎无法弄清楚变换后的x / y位置:
ctx.translate(canvas.width/2,canvas.height/2);
如你所见,图像会旋转,但是当它向左/向右旋转时,它会离开画布,我如何压缩高度以强制它留在边框中,这里是我想要实现的一个例子旋转。
修改
由于这个问题似乎很受欢迎,我在这里发布解决方案而不是JSFiddle
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var angleInDegrees=0;
var image=document.createElement("img");
image.onload=function(){
ctx.drawImage(image,(canvas.width - image.width) / 2, (canvas.height - image.height) / 2,image.width, image.height);//ctx.drawImage(img, x, y, width, height)
}
image.src="http://www.farmvertical.com/wp-content/uploads/2007/10/vertical_farm_v2.jpg";
$("#clockwise").click(function(){
angleInDegrees+=90;
drawRotated(angleInDegrees);
});
$("#counterclockwise").click(function(){
angleInDegrees-=90;
drawRotated(angleInDegrees);
});
function drawRotated(degrees){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.save();
ctx.translate(canvas.width/2,canvas.height/2);
ctx.rotate(degrees*Math.PI/180);
if(angleInDegrees%180==0){
ctx.drawImage(image, -image.width/2,-image.height/2);
}else{
ctx.drawImage(image, -image.width/2,-canvas.width/2,image.width, canvas.width);
}
ctx.restore();
}
答案 0 :(得分:2)
这是你想要的吗?
function drawRotated(degrees){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.save();
ctx.translate(canvas.width/2,canvas.height/2);
ctx.rotate(degrees*Math.PI/180);
if(angleInDegrees%180==0){
ctx.drawImage(image, -image.width/2,-image.height/2);
}else{
ctx.drawImage(image, -image.width/2,-canvas.width/2,image.width, canvas.width);
}
ctx.restore();
}