使用 HTML5 Canvas - 围绕任意点旋转图像 [英] using HTML5 Canvas - rotate image about arbitrary point

查看:34
本文介绍了使用 HTML5 Canvas - 围绕任意点旋转图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在作为背景的半圆形(北半球)图像顶部旋转表盘.范围可以是 0 - 180 度.在输入到执行画布转换的方法时,表盘将旋转并停在匹配的值上.这是我根据 phrogz

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

推荐答案

一般来说,你想做的是:

In general, what you want to do is:

  1. 将上下文转换为画布上对象应围绕其旋转的点.
  2. 旋转上下文.
  3. 通过对象内旋转中心的负偏移量转换上下文.
  4. 在 0,0 处绘制对象.

在代码中:

ctx.save();
ctx.translate( canvasRotationCenterX, canvasRotationCenterY );
ctx.rotate( rotationAmountInRadians );
ctx.translate( -objectRotationCenterX, -objectRotationCenterY );
ctx.drawImage( myImageOrCanvas, 0, 0 );
ctx.restore();

这是一个工作示例,展示了这一点.(旋转的数学只是实验性地破解,以找到适合快速绘制的仪表盘的弧度的摆动量和偏移量.)

Here's a working example showing 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.)

很明显,您可以用对 drawImage() 调用的偏移量替换上面第 3 步中的 translate 调用.例如:

As may be evident, you can substitute the translate call in step #3 above with offsets to the drawImage() call. For example:

ctx.drawImage( myImageOrCanvas, -objectRotationCenterX, -objectRotationCenterY );

当您要在同一位置绘制多个对象时,建议使用上下文转换.

Using context translation is recommended when you have multiple objects to draw at the same location.

这篇关于使用 HTML5 Canvas - 围绕任意点旋转图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆