Circle coordinates to array in Javascript

VirtuosiMedia picture VirtuosiMedia · Oct 1, 2008 · Viewed 18.4k times · Source

What's the best way to add the coordinates of a circle to an array in JavaScript? So far I've only been able to do a half circle, but I need a formula that returns the whole circle to two different arrays: xValues and yValues. (I'm trying to get the coordinates so I can animate an object along a path.)

Here's what I have so far:

circle: function(radius, steps, centerX, centerY){
    var xValues = [centerX];
    var yValues = [centerY];
    for (var i = 1; i < steps; i++) {
        xValues[i] = (centerX + radius * Math.cos(Math.PI * i / steps-Math.PI/2));
        yValues[i] = (centerY + radius * Math.sin(Math.PI * i / steps-Math.PI/2));
   }
}

Answer

Ates Goral picture Ates Goral · Oct 1, 2008

Your loop should be set up like this instead:

for (var i = 0; i < steps; i++) {
    xValues[i] = (centerX + radius * Math.cos(2 * Math.PI * i / steps));
    yValues[i] = (centerY + radius * Math.sin(2 * Math.PI * i / steps));
}
  • Start your loop at 0
  • Step through the entire 2 * PI range, not just PI.
  • You shouldn't have the var xValues = [centerX]; var yValues = [centerY]; -- the center of the circle is not a part of it.