Sometimes, we want to convert x,y coordinates to an angle with JavaScript.
In this article, we’ll look at how to convert x,y coordinates to an angle with JavaScript.
How to convert x,y coordinates to an angle with JavaScript?
To convert x,y coordinates to an angle with JavaScript, we use the Math.atan2
method.
For instance, we write
const deltaX = x2 - x1;
const deltaY = y2 - y1;
const rad = Math.atan2(deltaY, deltaX);
const deg = rad * (180 / Math.PI);
to get deltaX
and deltaY
by subtracting the x and y coordinates.
Then we call Math.atan2
with deltaY
and deltaX
to get the angle in radians.
Then we convert it to degrees by multiplying that by 180 / Math.PI
.
Conclusion
To convert x,y coordinates to an angle with JavaScript, we use the Math.atan2
method.