Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find degrees (0-360º) of point on a circle

I'm working on a small webapp in which I need to rotate shapes. I would like to achieve this by grabbing a point on a circle and dragging it around to rotate the image.

Here's a quick illustration to help explain things:

two points on circle, i'm looking to find the degrees of p1

My main circle can be dragged anywhere on the canvas. I know it's radius (r) and where 12 o'clock (p0) will always be (cx, cy - r). What I need to know is what degree p1 will be (0-360º) so I can rotate the contents of the main circle accordingly with Raphael.rotate().

I've run through a bunch of different JavaScript formulations to find this (example), but none seem to give me values between 0-360 and my basic math skills are woefully deficient.

The Color Picker demo (sliding the cursor along the ring on the right) has the behavior I want, but even after poring over the source code I can't seem to replicate it accurately.

Anything to point me in the correct direction would be appreciated.

like image 975
Darren Newton Avatar asked Jul 09 '11 15:07

Darren Newton


1 Answers

// Angle between the center of the circle and p1,
// measured in degrees counter-clockwise from the positive X axis (horizontal)
( Math.atan2(p1.y-cy,p1.x-cx) * 180/Math.PI + 360 ) % 360

The angle between the center of the circle and p0 will always be +90°. See Math.atan2 for more details.

like image 110
Phrogz Avatar answered Oct 20 '22 18:10

Phrogz