畫一波五角星: 美國隊長圖標
原理: (1)根據五角星的頂點,外頂點5個,內頂點5個,分成內外圓
(2)由三角函數可表示出每個頂點的位置
(3)利用canvas的lineTo()接口畫圖
上代碼:
1 <!DOCTYPE html> 2 <html lang="en"> 3 4 <head> 5 <meta charset="UTF-8"> 6 <title>Captain America</title> 7 <style type="text/css"> 8 #canvas { 9 display: block; 10 margin: 50px auto; 11 } 12 </style> 13 </head> 14 15 <body> 16 <canvas id="canvas"></canvas> 17 <script> 18 window.onload = function() { 19 var canvas = document.getElementById("canvas"); 20 canvas.width = 800; 21 canvas.height = 600; 22 23 var context = canvas.getContext("2d"); 24 // 四個圓 25 drawArc(context, 300, 300, 120, 0, Math.PI * 2, false, "#dd5870"); 26 drawArc(context, 300, 300, 100, 0, Math.PI * 2, false, "#e0dedf"); 27 drawArc(context, 300, 300, 80, 0, Math.PI * 2, false, "#dd5870"); 28 drawArc(context, 300, 300, 60, 0, Math.PI * 2, false, "#2773d3"); 29 drawStar(context, 20, 60, 300, 300, 0, "#dedce1"); // 五角星 30 } 31 32 function drawStar(ctx, r, R, x, y, changeDeg, fillColor) { 33 //繪制星星的路徑,changeDeg:表示五角星旋轉的角度 34 ctx.beginPath(); //開始路徑 35 for (var i = 0; i < 5; i++) { 36 ctx.lineTo(Math.cos((18 + i * 72 - changeDeg) / 180 * Math.PI) * R + x, -Math.sin((18 + i * 72 - changeDeg) / 180 * Math.PI) * R + y); 37 ctx.lineTo(Math.cos((54 + i * 72 - changeDeg) / 180 * Math.PI) * r + x, -Math.sin((54 + i * 72 - changeDeg) / 180 * Math.PI) * r + y); 38 } 39 ctx.closePath() //結束路徑 40 ctx.fillStyle = fillColor; 41 ctx.fill(); 42 } 43 44 function drawArc(ctx, x, y, r, stratAngel, endAngel, flag, fillColor) { 45 ctx.beginPath(); 46 ctx.arc(x, y, r, stratAngel, endAngel, flag); 47 ctx.fillStyle = fillColor; 48 ctx.fill(); 49 ctx.closePath(); 50 } 51 </script> 52 </body> 53 </html>
結果: