Skip to content Skip to sidebar Skip to footer

How Does One Rotate A Html Canvas Object Around A Fixed Point Using Mouse Action?

For example it may be used in the application of manually adjusting the hands of the clock. I guess it probably involves translating the needle (to make the end point of the needle

Solution 1:

In your example, you will want to calculate the angle between the centre of the clock face (black dot), and the current mouse position (red dot), relative to the Y axis (cardinal north if you imagine a compass).

If I remember my trig correctly, you can calculate this by using the following:

var angle = Math.atan2(y2 - y1, x2 - x1) * 180 / Math.PI;

// alter the angle to be relative to Y axis instead of X
angle += 90;
if(angle < 0) { angle = 360 + angle; }

In the formula, x and y are the coordinates of the two points, one of which you will know (it is the centre of the clock face), and the other you can get from the mouse move event.

Once you have the angle, you can simply translate to the the centre of the circle, rotate the canvas by the calculated amount, and draw the hand.

Update: I created a jsfiddle to illustrate the angle calculation:

http://jsfiddle.net/DAEpy/1/

rotation

Post a Comment for "How Does One Rotate A Html Canvas Object Around A Fixed Point Using Mouse Action?"