Canvas 矩形繪製提供三個直接方法,無需建立路徑,效能最佳:`fillRect`(填滿)、`strokeRect`(描邊)、`clearRect`(清除透明)。
ctx.fillRect(x, y, width, height)
ctx.strokeRect(x, y, width, height)
ctx.clearRect(x, y, width, height)
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #ccc"></canvas>
<script>
const ctx = document.getElementById('myCanvas').getContext('2d');
ctx.fillStyle = '#FF0000';
ctx.fillRect(0, 0, 150, 75); // 左上角 (0,0) 寬150 高75
</script>
</body>
</html>
<script>
const ctx = canvas.getContext('2d');
// 外框
ctx.strokeStyle = '#2c3e50';
ctx.lineWidth = 4;
ctx.strokeRect(10, 10, 180, 80);
// 內部清除一塊 (挖空效果)
ctx.clearRect(50, 30, 80, 40);
// 疊加半透明填滿
ctx.fillStyle = 'rgba(46, 204, 113, 0.5)';
ctx.fillRect(20, 20, 160, 60);
</script>
// 不佳:迴圈中重複設定樣式
for (const r of rects) {
ctx.fillStyle = r.color;
ctx.fillRect(r.x, r.y, r.w, r.h);
}
// 較好:依顏色分組
const byColor = rects.reduce((acc, r) => {
(acc[r.color] = acc[r.color] || []).push(r);
return acc;
}, {});
for (const [color, list] of Object.entries(byColor)) {
ctx.fillStyle = color;
for (const r of list) ctx.fillRect(r.x, r.y, r.w, r.h);
}
Canvas 矩形三大方法是 2D 繪圖基石。善用 `fillStyle`/`strokeStyle`/`lineWidth` 控制外觀,`clearRect` 實現遮罩/挖空效果。大量繪製時分組減少狀態切換提升效能。