How to determine the point on the canvas after turning the canvas

I am working on html5 canvas in which I draw a rectangle on the canvas.

  • Canvas is tarnslate in a central position.
  • Use the fillRect function to draw a rectangle
  • The canvas is absolute with respect to its parent div. His work is correct when the canvas is in its original position, but when I rotate the canvas 90/180/270 degrees, I canโ€™t tie the point by clicking on the screen and draw on the canvas. For example, when the canvas is in its original position, I can get a click on a click on the screen and then transfer this point to the canvas to draw a rectangle according to my translation position. But when I rotate the canvas 90/180/270 degrees, I can not convert this point on the screen to a point on the canvas. therefore, the shape is drawn in an odd / different position, and then actually clicked by the user.

My question is:

When the canvas rotates, how to translate the point that clicks on the screen to the point of drawing the canvas in accordance with its rotation

Any help is appreciated. Thanks in extended.

+4
source share
2 answers

I made a tiny conversion class for this very purpose:

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

Then you can use it as follows:

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] 

violin:

http://jsfiddle.net/DRf9P/

+8
source

I am affraid that we will have to use math.

Rotate the point with a negative rotation angle to get your position on the rotated plane using this equation:

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

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

where a negative rotation value

Now your point is on a normal plane without rotation, so the rest of the logic is like angle = 0

Here is a demo for you:

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

And here is the version with translation:

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

+6
source

Source: https://habr.com/ru/post/1398553/


All Articles