Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
144
rated 0 times [  145] [ 1]  / answers: 1 / hits: 88340  / 12 Years ago, thu, march 8, 2012, 12:00:00

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?


More From » function

 Answers
12

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

[#86991] Tuesday, March 6, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lizet

Total Points: 479
Total Questions: 96
Total Answers: 113

Location: Mexico
Member since Sun, Jul 25, 2021
3 Years ago
;