Html 使用 HTML5 Canvas - 围绕任意点旋转图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4649836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
using HTML5 Canvas - rotate image about arbitrary point
提问by Abhijit
Rotate the dial on top of a semi circular(Northern Hemisphere) image as background. range could be 0 - 180 degrees. on input to the method that does canvas transformation, the dial would rotate and stop over the matched value. Here's what I was trying based on help and sample passed on by phrogz
在作为背景的半圆形(北半球)图像顶部旋转表盘。范围可以是 0 - 180 度。在输入到进行画布转换的方法时,表盘将旋转并停在匹配的值上。这是我根据phrogz传递的帮助和样本尝试的方法
回答by Phrogz
In general, what you want to do is:
一般来说,你想做的是:
- Transform the context to the point on the canvas that the object should rotate about.
- Rotate the context.
- Transform the context by the negative offset within the object for the center of rotation.
- Draw the object at 0,0.
- 将上下文转换为画布上对象应围绕其旋转的点。
- 旋转上下文。
- 通过对象内旋转中心的负偏移量转换上下文。
- 在 0,0 处绘制对象。
In code:
在代码中:
ctx.save();
ctx.translate( canvasRotationCenterX, canvasRotationCenterY );
ctx.rotate( rotationAmountInRadians );
ctx.translate( -objectRotationCenterX, -objectRotationCenterY );
ctx.drawImage( myImageOrCanvas, 0, 0 );
ctx.restore();
Here's a working exampleshowing this in action. (The math for the rotation was just experimentally hacked to find a swing amount and offset in radians that fit the quickly-sketched gauge dial.)
这是一个显示此操作的工作示例。(旋转的数学只是实验性地破解,以找到适合快速绘制的仪表盘的弧度的摆动量和偏移量。)
As may be evident, you can substitute the translate
call in step #3 above with offsets to the drawImage()
call. For example:
很明显,您可以用translate
调用的偏移量替换上面第 3 步中的drawImage()
调用。例如:
ctx.drawImage( myImageOrCanvas, -objectRotationCenterX, -objectRotationCenterY );
Using context translation is recommended when you have multiple objects to draw at the same location.
当您要在同一位置绘制多个对象时,建议使用上下文转换。