使用canvas绘制多边形
效果如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<canvas id="canvas" width="800" height="400"></canvas>
<script>
const canvas = document.querySelector('#canvas');
c = canvas.getContext('2d');
// 定义一个以x,y为中心,半径为r的规则n边形
// 每个顶点都是都是均匀分布在圆周上
// 将第一个顶点放置在最上面,或者指定一个角度
// 最后一个参数表示是否顺时针
function polygon(c, n, x, y, r, angle, counterclockwise) {
angle = angle || 0;
counterclockwise = counterclockwise || false;
c.moveTo(x + r * Math.sin(angle), y - r * Math.cos(angle));
let delta = (2 * Math.PI) / n;
console.log(delta);
for (let i = 1; i < n; i++) {
angle += counterclockwise ? -delta : delta;
c.lineTo(x + r * Math.sin(angle), y - r * Math.cos(angle));
}
c.closePath();
}
c.beginPath();
polygon(c, 3, 50, 70, 50);
polygon(c, 4, 150, 60, 50, Math.PI / 4);
polygon(c, 5, 255, 55, 50);
polygon(c, 6, 365, 53, 50, Math.PI / 6);
polygon(c, 6, 365, 53, 20, Math.PI / 4, true);
// 设置属性控制图形的外观
// 内部使用灰色
c.fillStyle = '#ccc';
// 外部使用外边框
c.strokeStyle = '#008';
c.lineWidth = 5;
c.fill();
c.stroke();
</script>
</body>
</html>