1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Canvas 绘制五角星</title> </head> <body>
<canvas id="myCanvas" width="400" height="400" style="border:1px solid #d3d3d3;"> 您的浏览器不支持Canvas元素。 </canvas>
<script> var canvas = document.getElementById('myCanvas'); var ctx = canvas.getContext('2d');
function drawStar(cx, cy, spikes, outerRadius, innerRadius) { var rot = Math.PI / 2 * 3; var x = cx; var y = cy; var step = Math.PI / spikes;
ctx.beginPath(); ctx.moveTo(cx, cy - outerRadius)
for (i = 0; i < spikes; i++) { x = cx + Math.cos(rot) * outerRadius; y = cy + Math.sin(rot) * outerRadius; ctx.lineTo(x, y) rot += step
x = cx + Math.cos(rot) * innerRadius; y = cy + Math.sin(rot) * innerRadius; ctx.lineTo(x, y) rot += step }
ctx.lineTo(cx, cy - outerRadius); ctx.closePath(); ctx.lineWidth = 5; ctx.strokeStyle = 'black'; ctx.stroke(); ctx.fillStyle = 'yellow'; ctx.fill(); }
var centerX = canvas.width / 2; var centerY = canvas.height / 2; var spikes = 5; var outerRadius = 100; var innerRadius = 50;
drawStar(centerX, centerY, spikes, outerRadius, innerRadius); </script>
</body> </html>
|