How to convert x,y coordinates to an angle?

Solution 1:

If you get deltaX and deltaY from your coordinates then Math.atan2 returns the arctangent of the quotient of its arguments. The return value is in radians.

var deltaX = x2 - x1;
var deltaY = y2 - y1;
var rad = Math.atan2(deltaY, deltaX); // In radians

Then you can convert it to degrees as easy as:

var deg = rad * (180 / Math.PI)

enter image description here

Edit

There was some bugs in my initial answer. I believe in the updated answer all bugs are addressed. Please comment here if you think there is a problem here.

Solution 2:

The currently accepted answer is incorrect. First of all, Math.tan is totally wrong -- I suspect Mohsen meant Math.atan and this is just a typo.

However, as other responses to that answer state, you should really use Math.atan2(y,x) instead. The regular inverse tangent will only return values between -pi/2 and pi/2 (quadrants 1 and 4) because the input is ambiguous -- the inverse tangent has no way of knowing if the input value belongs in quadrant 1 vs 3, or 2 vs 4.

Math.atan2, on the other hand, can use the xy values given to figure out what quadrant you're in and return the appropriate angle for any coordinates in all 4 quadrants. Then, as others have noted, you can just multiply by (180/Math.pi) to convert radians to degrees, if you need to.