如何设置旋转后画布平移到左上角
我正在用简单的线条绘制一个符号,但希望用户能够指定旋转(仅限 90 度)。 这也意味着我的画布尺寸发生了变化。
不,我计算尺寸,并设置画布大小。然后,我将旋转中心设置为画布中心(通过 ctx.translate )并旋转到任意角度。
现在我的问题是:如何将翻译设置回左上角,以便我可以从该位置正常绘制符号?我真的必须通过旋转来计算值吗?
谢谢。
I'm drawing a symbol with simple lines, but want the user to be able to specify the rotation (in 90degrees only).
Which also means that the dimensions of my canvas change.
No I calculate the dimensions, and set the canvas size. Then I set the center of the rotation to the center of my canvas (via ctx.translate
) and rotate to the arbitrary degrees.
Now my problem is: How do I set the translation back to the upper left corner, so I can draw my symbol normally from that position? Do I really have to calculate the values with the rotation?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好问题!
translate
rotate
和scale
都是对当前矩阵进行操作的函数。这给了你很多选择。可能最简单的事情就是对上下文矩阵进行保存恢复现在,在调用恢复之后,矩阵恢复到上次保存之前的状态 - 在opengl中,这实际上是一个堆栈,您可以推送许多上下文,但是我不确定 webgl 是否支持这一点。
此链接也可能有帮助:https://developer.mozilla.org/en/drawing_graphics_with_canvas
希望这有帮助。
更新:
是的。好吧,所以你有点误解了。平移和旋转在绘图之前应用。这是因为有很多复杂的数学,并且确实超出了这个问题的范围。因此,如果您想绘制画布的一部分以一种方式旋转,而另一部分以不同的方式旋转,则首先
保存
,然后应用转换,执行绘图的第一部分,然后restore
返回到转换前的状态。此时,您可以重复。例如,您可以这样做:
通过这种方式,您有 1 个绘图函数,并且您只需在绘制不同的组件之前设置一个上下文即可。
Great question!
translate
rotate
andscale
are all functions that operate upon the current matrix. This gives you lots of options. Probably the simplest thing is to do a save restore on the context matrixNow after you call restore, the matrix reverts to how it was before the last save - In opengl, this is actually a stack, and you can push many contexts, but I'm not sure if webgl supports that.
This link may also be helpful: https://developer.mozilla.org/en/drawing_graphics_with_canvas
Hope this helps.
Update:
Yes. Okay, so you are misunderstanding something a little bit. The translations and rotations are applied before the drawing. This is because of a lot of complex math, and is really beyond the scope of this question. So if you want to draw part of your canvas rotated one way, and the other part of it rotated a different way, you first
save
, then apply the transformations, do the first part of the drawing, thenrestore
to get back to the pre-transformed state. At which point, you can repeat.So, for example, you can do this:
In this way, you have 1 drawing function, and you simply setup a context before you draw the different components.