angle = Math.atan2(y2 - y1, x2 - x1);
Where (x1, y1) and (x2, y2) are the coordinates of the two points.
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.