How to calculate an angle from points?

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;
}

Leave a Comment