2014-11-05 200 views
0

我想旋轉圖像,但根據圖像的寬度和高度調整畫布大小。請在js小提琴中看到我的代碼「http://jsfiddle.net/6ZsCz/1123/」。我實際上是旋轉基於畫布的圖像,但我的畫布具有固定的高度和寬度,因此圖像只是在內部旋轉。我想要這樣的東西。請檢查我附上的截圖。綠色邊框是一個畫布,所以如果我旋轉90度,那麼畫布應該展開高度並顯示整個圖像。圖像旋轉 - 基於圖像高度和寬度調整畫布大小

你能幫忙嗎?

HTML

<canvas id="canvas" ></canvas><br> 
<button id="clockwise">Rotate right</button> 

的Javascript

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,image.width,image.height); 
} 
image.src="http://www.ajaxblender.com/article-sources/images/plane-1.jpg"; 
$("#clockwise").click(function(){ 
    degrees+=90 
    ctx.clearRect(0,0,canvas.width,canvas.height); 
    ctx.save(); 
    ctx.translate(image.width/2,image.height/2); 
    ctx.rotate(degrees*Math.PI/180); 
    ctx.drawImage(image,0,0,image.width,image.height,-image.width/2,-image.height /2,image.width,image.height); 
    ctx.restore(); 
}); 

enter image description here

回答

2

首先初始化當圖像加載畫布大小:

image.onload=function(){ 
    canvas.width = image.width; 
    canvas.height = image.height;  
    ctx.drawImage(image,0,0); 
} 

現在您可以使用角度作爲畫布大小的基礎。如果爲0或180度,然後使用尺寸爲圖像相同,如果不交換尺寸:

if (degrees >= 360) degrees = 0; 

if (degrees === 0 || degrees === 180) { 
    canvas.width = image.width; 
    canvas.height = image.height; 
} 
else { 
    // swap 
    canvas.width = image.height; 
    canvas.height = image.width; 
} 

沒有必要清除畫布改變大小將其清除(否則會只需要當圖像包含透明度通道)。

你也想旋轉中心周圍的圖像畫布(雖然這裏不是一個大問題)。

Modified fiddle

+0

非常感謝你的快速幫助。還有一個問題。如果我使用Jquery UI調整圖像大小,那麼通常Jquery UI會在圖像上添加style =「width,height」,然後如果我旋轉圖像,那麼它只是根據圖像原始尺寸旋轉它,而不是從調整大小的圖像尺寸。請參閱我的[更新JS小提琴](http://jsfiddle.net/6ZsCz/1137/)**。是否有可能如果我調整圖像的大小,然後如果我旋轉圖像,那麼它只是基於調整大小的尺寸旋轉? – orbnexus 2014-11-06 20:01:51

+1

@mak我在這裏更新了小提琴。在html圖像中添加一個id,讀取它的w/h,將它設置在canvas上,並使用它與drawImage,你應該沒問題:http://jsfiddle.net/epistemex/bfwdqgm3/如果仍然不清楚只是打開一個新問題。希望這可以幫助! – K3N 2014-11-07 01:37:08

相關問題