在画布中旋转图像并保持其可拖动
我有一个在画布上绘制的图像。当鼠标单击并拖动时,我获取鼠标坐标并使用它们来设置图像的 X 和 Y 位置。完成后,我重新绘制画布。这就像一个魅力,我可以在画布上移动图像。
但现在我制作了 2 个按钮,这样我就可以左右旋转图像。当我旋转图像时,它现在相对于我旋转的角度移动。因此,当我将图像旋转 180 度并向上拖动图像时,它会向下移动!我不知道为什么会发生这种情况,也不知道我该如何弥补。 :(
嗯,我知道我可能有点含糊,所以这里是问题的演示。
I have an image that I draw on a canvas. When the mouse clicks and drags, I get the mouse coordinates and use them to set the position X and Y of the image. After that's been done, I redraw the canvas. That works like a charm and I can move the image over the canvas.
But now I make 2 buttons, so I can rotate the image left and right. When I rotate the image, it now moves relative to the angle I have rotated. So when I rotate the image 180 degrees and drag the image up, it goes down! I don't know why this happens or how I can compensate for it. :(
Well, I understand I may be a bit vague so here is a demo of the problem.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我无法访问您提供的演示网址,但这应该是通用的。
您需要将对象移动到坐标空间
o:(0,0)
的底部,进行旋转,然后将对象移回到移动之前的位置,因为所有你的变换被加入到一个单一的变换矩阵中,变换的顺序非常重要,你基本上只需要相反地进行它们,即将你的对象移回其初始位置,然后旋转它,然后将它移动到坐标空间基地:瞧。
这是演示:http://jsfiddle.net/ArtBIT/CdbWx/1
I cannot access the demo url you provided, but this should be universal.
You need to move your object to the base of your coordinate space
o:(0,0)
, do your rotation, and then move your object back to where it was before you moved it, and since all your transformations are joined into a single transformation matrix, the order of transformations is very important, and you basically just need to do them inversely, i.e. move your object back to its initial position, then rotate it, and then move it to the coordinate space base:And voila.
Here's the demo: http://jsfiddle.net/ArtBIT/CdbWx/1
交换这两行。
尝试先旋转然后平移
try to swap this two lines
first rotate and then translate.
与 ArtBIT 的答案类似,但考虑到您想从中心旋转,我将使用以下代码:
Similar to ArtBIT's answer, but taking into consideration you wanting to rotate from the center, I would use the code: