简体   繁体   English

在画布中旋转图像并使其可拖动

[英]Rotating an image in canvas and keeping it draggable

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 positionX and Y of the image. 当鼠标单击并拖动时,我得到了鼠标坐标,并使用它们来设置图像的positionX和Y。 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 180deg and drag the image up it goes down! 因此,当我将图像旋转180度并向上拖动图像时,它就会掉下来! 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. 好吧,我知道我可能有点含糊,所以这里是问题的演示。

I cannot access the demo url you provided, but this should be universal. 我无法访问您提供的演示URL,但这应该是通用的。

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, ie move your object back to its initial position, then rotate it, and then move it to the coordinate space base: 您需要将对象移动到坐标空间o:(0,0)的底部,进行旋转,然后再将对象移回移动之前的位置,因为所有转换都合并为一个变换矩阵,变换的顺序非常重要,您基本上只需要反向进行变换,即将对象移回其初始位置,然后旋转,然后将其移至坐标空间库:

ctx.translate(objects_x_position, objects_y_position);
ctx.rotate(angle);
ctx.translate(-objects_x_position, -objects_y_position);

And voila. 和瞧。 Here's the demo: http://jsfiddle.net/ArtBIT/CdbWx/1 这是演示: http : //jsfiddle.net/ArtBIT/CdbWx/1

try to swap this two lines 尝试交换这两行

oContext.translate(oImage.size.x /2 ,oImage.size.y / 2);
oContext.rotate(oImage.rotate * Math.PI/180);

first rotate and then translate. 首先旋转然后平移。

Similar to ArtBIT's answer, but taking into consideration you wanting to rotate from the center, I would use the code: 与ArtBIT的答案类似,但考虑到您想从中心旋转,我将使用以下代码:

ctx.translate(width/2, height/2);
ctx.translate(objects_x_position, objects_y_position);
ctx.rotate(angle);
ctx.translate(-objects_x_position, -objects_y_position);
ctx.translate((width/-2), height/-2); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM