矩形是 Canvas 裡最基礎的圖形,而且內建了專用方法,不需要像圓形那樣自己 beginPath。
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #c3c3c3;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script type="text/javascript">
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(0, 0, 150, 75);
</script>
</body>
</html>
ctx.fillRect(x, y, width, height) // 填滿的矩形 ctx.strokeRect(x, y, width, height) // 只有外框 ctx.clearRect(x, y, width, height) // 清空指定區域(變透明)
四個參數分別是左上角 x 座標、y 座標、寬與高。範例中的 fillRect(0, 0, 150, 75) 就是在原點畫一個 150×75 的紅色方塊。
// 填色 ctx.fillStyle = 'rgba(76, 175, 80, 0.6)'; // 支援 RGBA 透明度 ctx.fillRect(10, 10, 60, 40); // 外框 ctx.strokeStyle = '#2196f3'; ctx.lineWidth = 4; ctx.strokeRect(80, 10, 60, 40);
要注意 strokeRect 的線條是以路徑為中心向外向外各一半,因此線寬為 4 時,實際視覺邊界會超出宣告的座標 2px。若要求像素級精準對齊(例如畫格線),建議把座標設為半像素值或線寬設為奇數。
function animate() {
ctx.clearRect(0, 0, c.width, c.height); // 每幀先清乾淨,避免殘影
// ... 重新繪製這一幀的內容
requestAnimationFrame(animate);
}
做動畫時,「每幀清空 → 重畫」是最基本的骨架。
把 fillRect 與 clearRect 混合使用,就能做出長條圖、進度條、 heatmap 等元件。若需要圓角矩形,Canvas 目前提供了 ctx.roundRect(x, y, w, h, r)(較新的瀏覽器支援),舊環境則可用 arcTo() 自行拼出。
ctx.beginPath(); ctx.roundRect(10, 10, 120, 50, 8); ctx.fill();