實例
創建一個圓形:
var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); ctx.beginPath(); ctx.arc(100,75,50,0,2*Math.PI); ctx.stroke();
瀏覽器支持
Internet Explorer 9、Firefox、Opera、Chrome 以及 Safari 支持 arc() 方法。
注釋:Internet Explorer 8 或更早的瀏覽器不支持 <canvas> 元素。
定義和用法
arc() 方法創建弧/曲線(用於創建圓或部分圓)。
提示:如需通過 arc() 來創建圓,請把起始角設置為 0,結束角設置為 2*Math.PI。
提示:請使用 stroke() 或 fill() 方法在畫布上繪制實際的弧。
- 中心:arc(100,75,50,0*Math.PI,1.5*Math.PI)
- 起始角:arc(100,75,50,0,1.5*Math.PI)
- 結束角:arc(100,75,50,0*Math.PI,1.5*Math.PI)
JavaScript 語法:
context.arc(x,y,r,sAngle,eAngle,counterclockwise);
參數值
參數 | 描述 |
---|---|
x | 圓的中心的 x 坐標。 |
y | 圓的中心的 y 坐標。 |
r | 圓的半徑。 |
sAngle | 起始角,以弧度計。(弧的圓形的三點鍾位置是 0 度)。 |
eAngle | 結束角,以弧度計。 |
counterclockwise | 可選。規定應該逆時針還是順時針繪圖。False = 順時針,true = 逆時針。 |
為大家介紹曲線的語法。 如果要創建一個圓形,我們可以使用arc()方法。
語法:arc(定義一個中心點,半徑,起始角度,結束角度,和繪圖方向:順時針或逆時針)
代碼:context.arc(centerX, centerY, radius, startingAngle, endingAngle, antiClockwise);
HTML5 Canvas Arc 說明:
八卦圖示例代碼:
程序效果如下:
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8" /> <title>無標題文檔</title> <!--下面excanvas.js需下載才能在IE下支持canvas--> <!--[if IE]> <script src="http://a.tbcdn.cn/p/fp/2011a/html5.js"></script> <script src="http://api.html5media.info/1.1.4/html5media.min.js"></script> <script src="excanvas.js"></script> <![endif]--> <script type="text/javascript"> window.onload = function(){ var ctx = document.getElementByIdx_x_x_x("pic").getContext('2d'); //繪制白色半圓的代碼如下: ctx.beginPath(); ctx.arc(200,200,80,1.5*Math.PI,Math.PI/2,false); ctx.fillStyle="white"; ctx.closePath(); ctx.fill(); //繪制黑色半圓的代碼如下: ctx.beginPath(); ctx.arc(200,200,80,Math.PI/2,1.5*Math.PI,false); ctx.fillStyle="black"; ctx.closePath(); ctx.fill(); //繪制黑色小圓 ctx.beginPath(); ctx.arc(200,240,40,0,Math.PI*2,true); ctx.fillStyle="black"; ctx.closePath(); ctx.fill(); //繪制白色小圓 ctx.beginPath(); ctx.arc(200,160,40,0,Math.PI*2,true); ctx.fillStyle="white"; ctx.closePath(); ctx.fill(); //繪制白色小圓心 ctx.beginPath(); ctx.arc(200,160,5,0,Math.PI*2,true); ctx.fillStyle="black"; ctx.closePath(); ctx.fill(); //繪制黑色小圓心 ctx.beginPath(); ctx.arc(200,240,5,0,Math.PI*2,true); ctx.fillStyle="white"; ctx.closePath(); ctx.fill(); //繪制文字代碼如下: ctx.save(); ctx.fillStyle="black"; ctx.globalAlpha="0.4"; ctx.textAlign="center"; ctx.font="32px Arial"; ctx.shadowColor="rgba(0,0,0,0.4)"; ctx.shadowOffsetX=15; ctx.shadowOffsetY=-10; ctx.shadowBlur=2; ctx.fillText('Hello Canavs',200,100);//IE不支持 ctx.restore(); } </script> </head> <body> <canvas id="pic" width="400" height="400" style="border:1px solid; background:#E1E1FF;"></canvas> </body> </html>