Math.atan2 to find direction of a vector

suggest change

If you are working with vectors or lines you will at some stage want to get the direction of a vector, or line. Or the direction from a point to another point.

Math.atan2(y, x) returns the angle in radians, from -Math.PI to Math.PI (-180 to 180 degrees). Math.atan takes one argument and ignores a second. The y component comes first.

Direction of a vector

const vec = {x : 4, y : 3};
const dir = Math.atan2(vec.y, vec.x);  // 0.6435011087932844

Direction of a line

const line = {
    p1 : { x : 100, y : 128},
    p2 : { x : 320, y : 256}
}
// get the direction from p1 to p2
const dir = Math.atan2(line.p2.y - line.p1.y, line.p2.x - line.p1.x); // 0.5269432271894297

Direction from a point to another point

const point1 = { x: 123, y : 294};
const point2 = { x: 354, y : 284};
// get the direction from point1 to point2
const dir = Math.atan2(point2.y - point1.y, point2.x - point1.x); // -0.04326303140726714

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents