2014-11-05 211 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

相关问题