Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating evenly spaced points on the perimeter of a circle

The math behind this question has been asked numerous times, so that's not specifically what I'm after. Rather, I'm trying to program the equation for determining these points into a loop in JavaScript, so that I can display points the evenly around the circle.

So with the equations for the X and Y positions of the points:

pointX = r * cos(theta) + centerX 
pointY = r * sin(theta) + centerY

I should be able to calculate it with this:

var centerX = 300;
var centerY = 175;
var radius = 100;
var numberOfPoints = 8;
var theta = 360/numberOfPoints;

for ( var i = 1; i <= numberOfPoints; i++ ) {

    pointX = ( radius * Math.cos(theta * i) + centerX );
    pointY = ( radius * Math.sin(theta * i) + centerY );
    // Draw point ( pointX , pointY )
}

And it should give me the x,y coordinates along the perimeter for 8 points, spread 45° from each other. But this doesn't work, and I'm not understanding why.

This is the output that I get (using the HTML5 Canvas element). The points should reside on the innermost red circle, as that one has a

Incorrect:

When it "should" look like this (although this is with just 1 point, placed manually):

Correct:

Could someone help me out? It's been years since I took trig, but even with looking at other examples (from various languages), I don't see why this isn't working.

like image 810
SalarianEngineer Avatar asked Jun 17 '14 21:06

SalarianEngineer


2 Answers

Update: Figured it out!

I didn't need to add the centerX and centerY to each calculation, because in my code, those points were already relative to the center of the circle. So, while the canvas center was at point (300, 175), all points were relative to the circle that I created (the stroke line that they need to be placed on), and so the center for them was at (0, 0). I removed this from the code, and split the theta and angle calculations into two variables for better readability, and voila!

totalPoints = 8;

for (var i = 1; i <= totalPoints  ; i++) {
    drawPoint(100, i, totalPoints);
}

function drawPoint(r, currentPoint, totalPoints) {  

    var theta = ((Math.PI*2) / totalPoints);
    var angle = (theta * currentPoint);

    electron.pivot.x = (r * Math.cos(angle));
    electron.pivot.y = (r * Math.sin(angle));

    return electron;
}

Correct:

like image 100
SalarianEngineer Avatar answered Oct 01 '22 03:10

SalarianEngineer


cos and sin in Javascript accept an argument in radians, not degrees. You can change your theta calculation to

var theta = (Math.PI*2)/numberOfPoints;

See the Math.cos documentation for details

like image 24
Emmett Butler Avatar answered Oct 01 '22 03:10

Emmett Butler