1 繪制圓形(arc)
ctx.arc(x,y,r,sAngle,eAngle,counterclockwise);
x,y圓心坐標,r半徑;
sAngle,eAngle:起始,結束角度。
counterclockwise:是否是逆時針。true為逆時針,false為順時針(默認)
弧度和角度的轉換公式: rad = deg*Math.PI/180
圓形上面的點的坐標的計算公式
x =x0 + Math.cos(rad) * R;//x0和y0是圓心點坐標
-
y =y0 + Math.sin(rad) * R;//注意都是弧度
<script> var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); //弧形:圓心,半徑,角度 var x0 = 200; var y0 = 200; var radius = 100; var Angle = 72; ctx.lineWidth = 2; ctx.strokeStyle = "red"; //角度都要轉成弧度 ctx.arc(x0,y0,radius,0,Angle*Math.PI/180,false); //counterclockwise:false 表示順時針(默認) ctx.stroke(); ctx.fillStyle = 'pink'; ctx.fill(); ctx.beginPath(); ctx.strokeStyle = "blue"; ctx.lineWidth = 6; ctx.arc(x0,y0,radius,Angle*Math.PI/180, 270*Math.PI/180,false); ctx.stroke(); //ctx.fillStyle = 'orange'; ctx.fill(); </script>
2 非零正交原則
ctx.fill();
注意:交叉路徑的填充問題,“非零環(huán)繞原則”,順逆時針穿插次數決定是否填充。
1.如果線段是與路徑的順時針部分相交,則計數器加1,
2.如果線段是與路徑的逆時針部分相交,則計數器減1,
3.若計數器最終結果不是0,在調用fill()方法時,瀏覽器就會對其進行填充;若為0,就不對其填充。
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
ctx.arc(250,250,200,0,2*Math.PI,true);
ctx.arc(250,250,100,0,2*Math.PI,false);
ctx.fillStyle = "pink";
ctx.fill();
</script>