How does one rotate a HTML canvas object around a fixed point using mouse action?

后端 未结 1 1349
天命终不由人
天命终不由人 2021-01-03 15:06

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

相关标签:
1条回答
  • 2021-01-03 15:51

    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

    0 讨论(0)
提交回复
热议问题