taquaki-satwo
11/27/2017 - 12:03 PM

Canvasで円上のN分点を結ぶ

JS-Canvasで円上のN分点を結ぶ

function drawPolygon(ctx, n, x, y, r, color) {
  ctx.strokeStyle = color;
  ctx.beginPath();
  for(let i=0; i<n; i++) {
    const t = i*2*Math.PI/n;
    for(var j=i+1; j<n; j++) {
      const s = j*2*Math.PI/n;
      ctx.moveTo(x+r*Math.cos(t), y+r*Math.sin(t));
      ctx.lineTo(x+r*Math.cos(s), y+r*Math.sin(s));
    }
  }
  ctx.stroke();
}

window.onload = function() {
  const canvas = document.getElementById('mycanvas');
  const ctx = canvas.getContext('2d');
  drawPolygon(ctx, 6, 170, 170, 150, 'darkblue');
  drawPolygon(ctx, 12, 490, 170, 150, 'darkblue');
  drawPolygon(ctx, 18, 810, 170, 150, 'darkblue');
}

JS-Canvasで円上のN分点を結ぶ

A Pen by Takaaki Sato on CodePen.

License.

canvas#mycanvas(width='1000' height='400')