canvas绘制多边形

时间:2022-02-08 03:59:16
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>canvas绘制多边形</title>
</head>
<body>
<canvas id="canvas" style="border: 1px solid darkcyan;" width="400" height="400"></canvas>

<script>
var c = document.getElementById("canvas").getContext("2d");
//定义一个以(x,y)为中心,半径为r的规则n边型;
//每个顶点都是均匀分布在圆周上
//将第一个顶点放置在最上面,或者指定一定角度
//除非最后一个参数是true,否则顺时针旋转
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));
var delta = 2*Math.PI/n;
for(var 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);

c.fillStyle
= "#ccc";
c.strokeStyle
= "#008";
c.lineWidth
= 5;
c.fill();
c.stroke();
</script>
</body>
</html>

canvas绘制多边形