Search code examples
javascriptjquerymathgeometryatan2

Specify origin of Math.atan2


Math.atan2() is a very useful function for calculating angles. However, I cannot wrap my head around one thing:

$(document).mousemove(function(event){
    r = Math.atan2(event.pageY, event.pageX);
    deg = r * 180/Math.PI;
    console.log(deg);   
})

console.log indicates that 0,0 from where the angle is being calculated is at the upper left corner of the screen. How would I go about calculating the angle from a different origin, say the centre of the screen?


Solution

  • You would subtract the coordinates of your origin from the coordinates that you want to find the angle of:

    r = Math.atan2(event.pageY - originY, event.pageX - originX);