Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an array of coordinates that make up a circle in canvas?

So, if this is the code I'm using to draw a circle on my canvas:

ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
ctx.lineWidth = 3;
ctx.strokeStyle = "black";
ctx.stroke();

... how could I get an array of coordinates of the points that make up this circle so I can save them in a database and load on canvas later using the context.moveTo() and context.lineTo() methods to connect the dots, drawing the same circle?

I guess I'm asking if it's possible to draw this kind of circle using not .arc() method but by connecting dots with lines, if I only know my center coordinates and circle radius (and of course the width of the line and color). This should enable me to save each dot coordinates in an array as I loop through.

like image 249
Zannix Avatar asked Mar 22 '23 17:03

Zannix


2 Answers

@Octopus is on the right track:

var centerX=100;
var centerY=100;
var radius=40;

// an array to save your points
var points=[];

for(var degree=0;degree<360;degree++){
    var radians = degree * Math.PI/180;
    var x = centerX + radius * Math.cos(radians);
    var y = centerY + radius * Math.sin(radians);
    points.push({x:x,y:y});
}

Then you can draw the circle using the point objects in the points array:

ctx.beginPath();
ctx.moveTo(points[0].x,points[0].y);
for(var i=1;i<points.length;i++){
    ctx.lineTo(points[i].x,points[i].y);
}
ctx.closePath();
ctx.fillStyle="skyblue";
ctx.fill();
ctx.strokeStyle="lightgray";
ctx.lineWidth=3;
ctx.stroke()

A suggestion, however...

Instead of saving all the points in the database, just save the centerX/Y and radius in the database.

Then you can use this same math to create the points and draw the circle.

like image 130
markE Avatar answered Apr 19 '23 18:04

markE


You are asking for the formula for a circle which is:

radius*radius = (x-centerX)*(x-centerX) + (y-centerY)*(y-centerY)

Or if you want to generate n points do something like this:

for (i=0;i<n;i++) {
    x[i] = centerX + radius* Math.cos( (i*2*Math.PI)/n );
    y[i] = centerY + radius*-Math.sin( (i*2*Math.PI)/n );
}
like image 28
Octopus Avatar answered Apr 19 '23 16:04

Octopus