2011-06-01 128 views
10

我在JavaScript中使用画布在HTML 5中绘制图像。我需要以旋转的角度画出它。我知道这可以通过使用画布上下文应用旋转(角度)函数来完成。但我需要这样做而不旋转画布本身在画布中以角度绘制图像而不旋转画布

如果可能的话,请提出可能的方法。

回答

6

实际上,您可以绘制任何想要旋转到屏幕外的画布并将其绘制到主画布中。我借了从谷歌IO对话验证码:

rotobj = rotateAndCache(myimg,myangle) 

,并在您drawcode:

rotateAndCache = function(image,angle) { 
    var offscreenCanvas = document.createElement('canvas'); 
    var offscreenCtx = offscreenCanvas.getContext('2d'); 

    var size = Math.max(image.width, image.height); 
    offscreenCanvas.width = size; 
    offscreenCanvas.height = size; 

    offscreenCtx.translate(size/2, size/2); 
    offscreenCtx.rotate(angle + Math.PI/2); 
    offscreenCtx.drawImage(image, -(image.width/2), -(image.height/2)); 

    return offscreenCanvas; 
} 

然后缓存它

mycontext.drawImage(rotobj,x_coord,y_coord) 

,如果你有一个对象这是唯一有用的它只旋转一次角度,随后仅进行变换。

+0

谢谢PeterT。这几乎符合我期待的法案。再次感谢。 – Vinayak 2011-06-03 06:40:40

+0

有没有机会与那次谈话联系? – Alexander 2011-06-11 03:49:24

+1

@Alexander实际上我是这样做的:http://www.google.com/events/io/2011/sessions/super-browser-2-turbo-hd-remix-introduction-to-html5-game-development.html视频是在http://www.youtube.com/watch?v=yEocRtn_j9s – PeterT 2011-06-12 00:44:56

0

这是不可能的,你可能不需要它。试试这个:

context.save() // Save current state (includes transformations) 
context.rotate() 
... draw image ... 
context.restore() // Restore state 
+0

有缩放图像,以类似的方式? – Kantesh 2011-07-01 09:21:54

3

当您在画布上应用转换时,您不会旋转画布。你只是告诉你所有你将要画的东西都会以特定的方式转变。如果要避免转换影响其他命令,请使用save()restore()方法。它们允许保存和恢复画布的设置。

ctx.save(); 
ctx.rotate(30); 
ctx.drawImage(); 
ctx.restore(); 
+0

有没有类似的方式来缩放图像? – Kantesh 2011-07-01 09:21:30

+0

是的,'scale'而不是'rotate'。还有两个参数,水平和垂直缩放因子。 – bjornd 2011-07-01 09:42:00

1

我已经upvoted @ PeterT--伟大的片段和运作良好 - 谢谢你!我必须做出3个小改变才能使它适用于我:

1.宽度和高度的最大值不够:如果考虑旋转正方形,则需要一个直径为对角线的圆的广场(var diam)。
2.画布需要翻回(或使用保存/恢复)。
3.对象的x和y坐标必须根据画布大小进行调整。

所以我结束了:

rotateAndCache = function(image,angle) { 
     var offscreenCanvas = document.createElement('canvas'); 
     var offscreenCtx = offscreenCanvas.getContext('2d'); 

     var size = Math.max(image.width, image.height); 
     var diam = 2*((size/2)*Math.sqrt(2));     // needs to be saved 
     offscreenCanvas.width = diam; 
     offscreenCanvas.height = diam; 

     offscreenCtx.translate(diam/2, diam/2); 
     offscreenCtx.rotate(angle); 
     offscreenCtx.drawImage(image, -(image.width/2), -(image.height/2)); 
     offscreenCtx.translate(-diam/2, -diam/2); 

     return offscreenCanvas; 
} 


和调整战平位置(需要保存在rotateAndCache):
mycontext.drawImage(rotobj,x-(diam-width)/2,y-(diam-height)/2);

+0

如果你想要精确,你需要一个直径等于矩形对角线的圆,所以它应该是'var diam = Math.sqrt(image.width * image.width + image.height * image .height);'但是,我明白你的意思。 – PeterT 2014-10-17 22:50:40

+0

是的,最大的维度是混乱的,我的意思是对角线。代码应该这样做(它是一个1-1根-2直角三角形) – dhc 2014-10-17 22:54:46

+0

但是,这是一个长度为'max(image.width,image.height)'的长方形的对角线,不是吗?它可能会或可能不会略大于边长不等的矩形(至少不会更小,因此不会导致错误)。 – PeterT 2014-10-17 22:56:40