1

I have a square (100px x 100px) with origin at 0,0 (upper left). When I move the mouse, lets say 10 pixel x and y, I move the origin according to displacement and then origin becomes 10,10, simple. Works fine!

When I rotate the square, my rotation function rotates it fine, but then, after the square is rotated, lets say 10 degrees, the origin point should be move accordingly to the rotation. And now, I have no idea of the formula I have to apply to make it append!

I wikipedia, but I tink it's too complicated.

http://en.wikipedia.org/wiki/Angular_displacement

and

http://en.wikipedia.org/wiki/Cosine#Sine.2C_cosine.2C_and_tangent

Example: After a 90 deg rotation to the left, the origin is now at : lower left, now when I move the mouse to to right, the picture go UP!!!!

Ben Brocka
  • 2,006
  • 4
  • 34
  • 53
menardmam
  • 9,860
  • 28
  • 85
  • 113
  • I think this question may belong on http://math.stackexchange.com/ – ewok Oct 26 '11 at 20:07
  • 1
    Are you looking to rotate the square around the center of it? If so, this forum post might help: http://www.gamedev.net/topic/532033-how-to-rotate-a-square-by-an-angle-image/ – Dan W Oct 26 '11 at 20:08
  • Are you trying to reverse the transform to convert a mouse position on the rotated square to the corresponding point on the original square? [This question](http://stackoverflow.com/questions/2244157/reverse-java-graphics2d-scaled-and-rotated-coordinates) may be relevant. – finnw Oct 26 '11 at 21:14

2 Answers2

2

If I understand your problem correctly, you are applying an offset to the rectangle points based on your mouse position, then rotating the resulting points about the origin.

Instead, try applying your mouse offset after you do your rotation, not before.

comingstorm
  • 25,557
  • 3
  • 43
  • 67
1

Suppose you have a figure and you want to rotate it by angle alpha and translate it so that point (cx, cy) of the figure gets to point (sx, sy) after the transformation.

enter image description here

The transformation is

transformed_x = x*cos(alpha) - y*sin(alpha) + offset_x
transformed_y = x*sin(alpha) + y*cos(alpha) + offset_y

to compute desired offset_x and offset_y values you just need to put your requirement about (cx, cy) and (sx, sy) into the above equations:

sx = cx*cos(alpha) - cy*sin(alpha) + offset_x
sy = cx*sin(alpha) + cy*cos(alpha) + offset_y

and now you can easily extract the offset values from that:

offset_x = sx - cx*cos(alpha) + cy*sin(alpha)
offset_y = sy - cx*sin(alpha) - cy*cos(alpha)

To set up canvas transform for it you need just to call

context.translate(sx - cx*Math.cos(alpha) + cy*Math.sin(alpha),
                  sy - cx*Math.sin(alpha) - cy*Math.cos(alpha));
context.rotate(alpha);

You can see a little demo of this formula following this link.

6502
  • 112,025
  • 15
  • 165
  • 265