Search code examples
javascriptfunctioncoordinatesangle

How to calculate an angle from points?


I want to get a simple solution to calculate the angle of a line (like a pointer of a clock).

I have 2 points:

cX, cY - the center of the line.
eX, eY - the end of the line.

The result is angle (0 <= a < 360).

Which function is able to provide this value?


Solution

  • You want the arctangent:

    dy = ey - cy
    dx = ex - cx
    theta = arctan(dy/dx)
    theta *= 180/pi // rads to degs
    

    Erm, note that the above is obviously not compiling Javascript code. You'll have to look through documentation for the arctangent function.

    Edit: Using Math.atan2(y,x) will handle all of the special cases and extra logic for you:

    function angle(cx, cy, ex, ey) {
      var dy = ey - cy;
      var dx = ex - cx;
      var theta = Math.atan2(dy, dx); // range (-PI, PI]
      theta *= 180 / Math.PI; // rads to degs, range (-180, 180]
      //if (theta < 0) theta = 360 + theta; // range [0, 360)
      return theta;
    }