I am working on html5 canvas app in which i draw rectangle on canvas.
My Question:
When canvas is rotated, how to translate the point that is click on screen to canvas draw point as per its rotation
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.
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.
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.
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/
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With