How to Find the Angle Between Two Points in JavaScript

08/01/2021

Contents

In this article, you will learn how to find the angle between two points in JavaScript.

Finding the angle between two points in JavaScript

To find the angle between two points in JavaScript, you can use the Math.atan2() method. This method returns the arctangent of the quotient of its arguments, which represents the angle between the positive x-axis and the line connecting the two points. Here is the formula:

angle = Math.atan2(y2 - y1, x2 - x1);

Where (x1, y1) and (x2, y2) are the coordinates of the two points.

Examples

Here is an example of how to use this formula in JavaScript:

const x1 = 1;
const y1 = 2;
const x2 = 4;
const y2 = 6;

const angle = Math.atan2(y2 - y1, x2 - x1);

console.log(angle); // Output: 1.1071487177940904

In this example, we have two points with coordinates (1, 2) and (4, 6). We use the Math.atan2() method to calculate the angle between these two points, which is approximately 1.107 radians or 63.434 degrees.

We start by defining the coordinates of the two points, and then use the Math.atan2() method to calculate the angle between them. The Math.atan2() method takes two arguments, which represent the y and x differences between the two points. We subtract the y and x coordinates of the first point from those of the second point, respectively, to get these differences.

We then assign the result to the angle variable and log it to the console to verify that it is correct.

You can use this formula and code to find the angle between any two points in a 2D plane. Note that the Math.atan2() method returns the angle in radians, so you may need to convert it to degrees using the Math.degrees() method if necessary.