画一个五角星
<body>
<canvas id="canvas"></canvas>
<script>
window.onload=function(){
canvas=document.getElementById("canvas");
canvas.width=800;
canvas.height=800;
var context=canvas.getContext("2d")
context.beginPath();
for(var i=0;i<5;i++){
context.lineTo(Math.cos((18+i*72)/180*Math.PI)*300+400,
-Math.sin((18+i*72)/180*Math.PI)*300+400
);
context.lineTo(Math.cos((54+i*72)/180*Math.PI)*150+400,
-Math.sin((54+i*72)/180*Math.PI)*150+400
)
}
context.closePath();
context.lineWidth=10;
context.fillStyle="pink";
context.stroke();
context.fill()
}
</script>
</body>
函数化 (并让五角星顺时针旋转顺30度角)
<body>
<canvas id="canvas"></canvas>
<script>
window.onload=function(){
canvas=document.getElementById("canvas");
canvas.width=800;
canvas.height=800;
var context=canvas.getContext("2d");
draw(context,150,300,400,400,30)
}
function draw(ctx,r,R,x,y,rot){
ctx.beginPath();
for(var i=0;i<5;i++){
ctx.lineTo(Math.cos((18+i*72-rot)/180*Math.PI)*R+x,
-Math.sin((18+i*72-rot)/180*Math.PI)*R+y
);
ctx.lineTo(Math.cos((54+i*72-rot)/180*Math.PI)*r+x,
-Math.sin((54+i*72-rot)/180*Math.PI)*r+y
)
}
ctx.closePath();
ctx.lineWidth=10;
ctx.fillStyle="pink";
ctx.stroke();
ctx.fill();
}
</script>
</body>