canvas繪制多邊形
阿新 • • 發佈:2017-11-18
col 分布 borde canvas 分享圖片 tel utf-8 pat ()
<!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繪制多邊形