trigonometry
Math.atan2
Returns the angle in radians between the positive x-axis and the point (x, y), in the range (-π, π]. Note the argument order: y first, then x.
Math.atan2(y, x) Parameters & edge cases
| Case | Behavior |
|---|---|
| y | The y-coordinate — the FIRST argument |
| x | The x-coordinate — the SECOND argument |
| quadrant | Unlike Math.atan(y/x), atan2 uses the signs of both to pick the correct quadrant |
| range | Returns a value in (-π, π] |
Examples
console.log(Math.atan2(1, 1)); // 0.7853981633974483 π/4 — 45° above the positive x-axis.
console.log(Math.atan2(1, 0)); // 1.5707963267948966 π/2 — straight up.
console.log(Math.atan2(0, -1)); // 3.141592653589793 π — pointing left along the negative x-axis.
console.log(Math.atan2(-1, -1)); // -2.356194490192345 -3π/4 — third quadrant, correctly signed unlike atan(-1/-1).
Gotcha
Argument order is (y, x), not (x, y) — a leading source of bugs. Use atan2 (not atan(y/x)) whenever you need the true polar angle of a 2D point.
Related
Math.sin
Returns the sine of an angle expressed in radians. Result is always in the range [-1, 1].
Math.cos
Returns the cosine of an angle expressed in radians. Result is always in [-1, 1].
Math.tan
Returns the tangent of an angle expressed in radians. Equal to sin(x) / cos(x) and unbounded near π/2 + kπ.