DanteAligante
DanteAligante

Reputation: 23

Convert a circle to a poly line in JavaScript

I have as input the radius of a circle and the coordinates X and Y of the center. I would like to have in output the coordinates of a connected series of line segments (a polygonal chain) that approximates the circle. Is there a method for doing so in JavaScript?

Upvotes: 1

Views: 156

Answers (1)

Daniel Manta
Daniel Manta

Reputation: 6718

We use a canvas and context.lineTo(x, y); to draw polygons in Javascript. To get the segments, iterate while incrementing angle with the parametric equation of the circle:

let x = center.x + radius * Math.cos(angle);
let y = center.y + radius * Math.sin(angle);  

This is working sample:

let radius = 50;
let segments = 10;
let segmentAngle = Math.PI * 2 / segments;
let center = { x: 100, y: 75 };
let points = [];
for (let angle = 0; angle < 2 * Math.PI; angle += segmentAngle) {
  points.push({
    x: center.x + 50 * Math.cos(angle),
    y: center.y + 50 * Math.sin(angle)
  });
};
paintSegments(points);
console.log(points);

function paintSegments(points) {
  let canvas = document.getElementById("myCanvas");
  let context = canvas.getContext("2d");
  context.beginPath();
  points.forEach(function(point) {
    context.lineTo(point.x, point.y);
  });
  context.lineTo(center.x + radius, center.y);
  context.stroke();
}
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">Your browser does not support the HTML5 canvas tag.</canvas>

Upvotes: 1

Related Questions