2013-10-25 197 views
2

我希望允许用户旋转画布,同时改变尺寸,如果他们在旋转后不再适合,这里是一个小提琴:HTML5旋转画布图像

http://jsfiddle.net/6ZsCz/84/

我似乎无法找出转换后的x/y的位置:

ctx.translate(canvas.width/2,canvas.height/2); 

正如你看到的,图像不旋转,但是当它旋转左/右它熄灭的画布,我怎么能压缩的高度,以迫使它留在边界,这里是我想要在它旋转时进行存档的一个示例。

enter image description here

编辑:

,因为这个问题似乎很流行,我在这里代替的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(); 
} 

回答

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(); 
} 
+0

是的!谢谢一堆! –