Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to detect point on canvas after canvas rotation

I am working on html5 canvas app in which i draw rectangle on canvas.

  1. Canvas is tarnslate to center position
  2. Use fillRect function to draw rectangle
  3. Canvas is position absolute with respect to its parent div. Its work properly when canvas is at original position but when I rotate canvas 90/180/270 degree i am not able to relate point clicked on screen and point to draw on canvas. For eg: when canvas is at original position i am able to get point click on screen and then transferal that point to canvas point to draw rectangle as per my translate position. But when i rotate canvas by 90/180/270 degree, i am not able to convert that screen point to canvas point. so the shape is drawn at odd/different position then actually click by user.

My Question:

When canvas is rotated, how to translate the point that is click on screen to canvas draw point as per its rotation

like image 582
Sanket Avatar asked Feb 27 '12 07:02

Sanket


People also ask

How do I reset my canvas orientation?

You can reset via the View menu / Canvas Orientation / Reset Rotation. Or, look at the very bottom right of the screen. You'll see a box labelled 'R' where you enter degrees. Enter zero in the box and hit enter.

How do you stop a canvas from rotating?

Under Preferences -> Keyboard Shortcuts there is a Reset Rotation command which can be assigned a key command. I set mine to numpad zero which works wonderfully.

How do you rotate elements in canvas?

The rotate() method allows you to rotate a drawing object on the canvas. The rotate() method accepts a rotation angle in radians. If the angle is positive, the rotation is clockwise. In case the angle is negative, the rotation is counterclockwise.


2 Answers

I made a tiny transform class for this very purpose:

https://github.com/simonsarris/Canvas-tutorials/blob/master/transform.js

You can then use it like this:

var t = new Transform();
console.log(t.transformPoint(5,6)); // will be just [5,6]
// apply the same transformations that you did to the canvas
t.rotate(1);
console.log(t.transformPoint(5,6)); // will be [-2.347, 7.449]

fiddle:

http://jsfiddle.net/DRf9P/

like image 187
Simon Sarris Avatar answered Nov 14 '22 23:11

Simon Sarris


I am affraid that we will have to use math.

Rotate a point by the negative value of rotation angle to get its position on rotated plane using this equation:

nX = x * cos(a) - y * sin(a)

nY = x * sin(a) + y * cos(a)

where a is negative of rotation value

Your point is now on normal not rotated plane so the rest of logic is just like when angle = 0

Here is a demo fiddle for you:

http://jsfiddle.net/Q6dpP/5/

And here is a version with translation:

http://jsfiddle.net/Q6dpP/6/

like image 33
rezoner Avatar answered Nov 15 '22 00:11

rezoner