I’m trying to generate a polygon with circles inside (JS canvas
). Here’s a sample expected output:
It’s basically a 4-sided polygon (square) with circles next to the vertices. Here is what I tried:
However, I don’t get the expected outcome.
Note: I want this to work for any sized polygon and not just a square. Also, stopping the draw()
function to execute gives me a proper square. I believe there’s a problem in the draw()
function. Any help is appreciated 🙂
function draw(x, y, ctx){
ctx.arc(x, y, 4, 0, Math.PI * 2);
ctx.fillStyle = "#283149";
ctx.fill(); // create circle
}
function createPolygon(n){
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext('2d');
ctx.reset();
var size = 60, Xcenter = 80, Ycenter = 80;
ctx.beginPath();
ctx.moveTo (Xcenter + size * Math.cos(0), Ycenter + size * Math.sin(0));
for (var i = 1; i <= n; i++) {
ctx.lineTo (Xcenter + size * Math.cos(i * 2 * Math.PI / n), Ycenter + size * Math.sin(i * 2 * Math.PI / n));
draw(Xcenter + Math.cos(i * 2 * Math.PI / n), Ycenter + Math.sin(i * 2 * Math.PI / n), ctx);
}
ctx.fillStyle = "#00818A"
ctx.fill();
}
<button onclick="createPolygon(4)">Create 4</button>
<canvas id="canvas"></canvas>