js结合canvas画任意多边形

发布时间 2023-06-12 16:15:48作者: 小胖子的快乐

 实现六边形

// html
<canvas></canvas>

// js
const canvas = document.querySelector("canvas");
canvas.width = 400;
canvas.height = 200;

const ctx = canvas.getContext("2d");
const cx = 200;
const cy = 100;
const radius = 50;
ctx.translate(cx, cy);

for (let i = 0; i < 6; i++) {
    const rotation = (Math.PI / 3) * i;
    if (i === 0) {
    ctx.moveTo(radius * Math.cos(rotation), radius * Math.sin(rotation));
    } else {
    ctx.lineTo(radius * Math.cos(rotation), radius * Math.sin(rotation));
    }
}
ctx.closePath();
ctx.stroke();

封装

function drawShape(x, y, r, sides) {
  ctx.translate(x, y);

  for (let i = 0; i < sides; i++) {
    const rotation = ((Math.PI * 2) / sides) * i;
    if (i === 0) {
      ctx.moveTo(r * Math.cos(rotation), r * Math.sin(rotation));
    } else {
      // for the rest draw a line
      ctx.lineTo(r * Math.cos(rotation), r * Math.sin(rotation));
    }
  }
  ctx.closePath();
  ctx.stroke();
  ctx.resetTransform();
}
绘制

绘制

drawShape(100, 100, 50, 3);
drawShape(225, 100, 50, 7);
drawShape(350, 100, 50, 4);