Archive

Posts Tagged ‘math’

Calculating the angle between two points on a circle

March 23, 2009 29 comments

I needed to calculate the angle between two points on the same circle. Don’t ask why, totally a new more complicated discussion.
So I had to remember a little trigonometry from the old days. Actually, this is done surprisingly easy, by simply using the atan2 method. Fortunately, this is available in JavaScript in the Math library.
In my problem, I had the center of the circle, one of the coordinates point(p1) and I had to find out the angle between the point (p0) at the 12-hour (imagine the circle as a clock) and the given one. Angle between two points on a circle

First of all the coordinates of the point at 12-hour is

p0(x,y) = (center.x, center.y - radius)

where radius is the circle radius and is calculated (according to Pythagorean theorem) as

radius = sqrt(|center.x - p1.x|<sup>2</sup> * |center.y - p1.y|<sup>2</sup>)

Now let’s calculate the angle:

angle = atan2(p1.y - p0.y, p1.x - p0.x)

This will return the angle in radians. If you want to translate it into the interval [0,2 π] then simply multiply by two. If you want to transform it to degrees use angle * 180 / π.
Below you have a JavaScript function that receives as arguments the coordinates of the center and second point and returns the angle in degrees in the interval (0°, 360°) between the 12-hour point and the second point

function angle(center, p1) {
var p0 = {x: center.x, y: center.y - Math.sqrt(Math.abs(p1.x - center.x) * Math.abs(p1.x - center.x)
+ Math.abs(p1.y - center.y) * Math.abs(p1.y - center.y))};
return (2 * Math.atan2(p1.y - p0.y, p1.x - p0.x)) * 180 / Math.PI;
}

I also wrote a small demo.

Later update:
As I had this question in the comments, in case you have the center coordinates, radius, angle and you want to calculate the second point coordinates, below is the JavaScript function. The first point is considered to be at 12’o clock.

function getPointAt(center, radius, angle) {
// Please note that the angle is given in radians;
// if given in degrees uncomment the line below
//angle *= Math.PI / 180;
return {x: center.x + Math.sin(Math.PI - angle) * radius,
y: center.y + Math.cos(Math.PI - angle) * radius};
}

All the coordinates are relative to the top left corner.