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.atan(yComponent, xComponent) return the angle in radius within the range of -Math.PI to Math.PI (-180 to 180 deg)

Direction of a vector

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

Direction of a line

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

Direction from a point to another point

var point1 = { x: 123, y : 294};
var point2 = { x: 354, y : 284};
// get the direction from point1 to point2
var 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