這是練習 Canvas 時最基礎的一題:用同一個 arc() 方法,透過「描邊」與「填充」的切換,就能畫出空心圓、實心圓,以及兩者疊加的樣子。
<canvas id="canvas" width="500" height="500" style="background-color: yellow;"></canvas>
var canvas = document.getElementById("canvas");
var cxt = canvas.getContext("2d");
// 1. 空心圓:畫完路徑後只呼叫 stroke()
cxt.beginPath();
cxt.arc(200, 200, 50, 0, 360, false);
cxt.lineWidth = 5;
cxt.strokeStyle = "green";
cxt.stroke();
cxt.closePath();
// 2. 實心圓:畫完路徑後只呼叫 fill()
cxt.beginPath();
cxt.arc(200, 100, 50, 0, 360, false);
cxt.fillStyle = "red"; // 不設定的話預設是黑色
cxt.fill();
cxt.closePath();
// 3. 空心 + 實心組合:fill() 與 stroke() 都呼叫
cxt.beginPath();
cxt.arc(300, 300, 50, 0, 360, false);
cxt.fillStyle = "red";
cxt.fill();
cxt.strokeStyle = "green";
cxt.stroke();
cxt.closePath();
arc(x, y, r, startAngle, endAngle, anticlockwise) 的起止角度單位為弧度,畫一整圈用 Math.PI * 2 最保險。true 代表逆時針、false 代表順時針。當起點與終點角度相同時,順時針會畫出完整一圈,逆時針則可能什麼都不畫,這是初學者常踩的坑。把這三種畫法互換組合,再搭配 lineCap 與不同 lineWidth,就能做出甜甜圈、進度環、雷達掃描等常見的 UI 元件。