萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

HTML5 Canvas 繪製矩形完整指南:fillRect、strokeRect、clearRect 三大方法

前言

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>

座標系統提醒

  • 原點 (0,0) 位於 Canvas **左上角**。
  • X 向右增、Y 向下增。
  • 寬高為負值時不會繪製(不會翻轉)。

效能優化:批次繪製

// 不佳:迴圈中重複設定樣式
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` 實現遮罩/挖空效果。大量繪製時分組減少狀態切換提升效能。

copyright © 萬盛學電腦網 all rights reserved