Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get angle in javascript between two points

image

in the above image ineed the angle between the two points

if green dot is considered as origin (px,py) ie (0,0) and red dot is (ax,ay)

by the way in the above image angle should be around 45 degree.... acute angle

more ex:

3:00 is 0 degree 12:00 is 90 degree 9:00 is 180 degree 6:00 is 270 degree

here's the code i have tried so far:

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;
}
like image 677
user10633681 Avatar asked Oct 26 '25 19:10

user10633681


1 Answers

Try this out, Working fine for me.

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;
}
like image 157
Dksingh Avatar answered Oct 28 '25 11:10

Dksingh