2013-10-25 237 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

是的!謝謝一堆! –