萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML5 教學

Canvas 矩形繪製三大方法:fillRect、strokeRect、clearRect 核心差異與組合技巧

矩形是 Canvas 唯一的內置基礎圖形,提供三種直接繪製方法。本文詳細對比 fillRect/strokeRect/clearRect 的差異、樣式屬性影響、組合繪製模式與實戰應用場景。

三大方法對比

方法效果受影響樣式屬性用途
fillRect(x,y,w,h)實心填充矩形fillStyle, globalAlpha, globalCompositeOperation, shadow*背景、色塊、實心圖形
strokeRect(x,y,w,h)描邊矩形框strokeStyle, lineWidth, lineCap, lineJoin, miterLimit, globalAlpha, shadow*邊框、框選、網格線
clearRect(x,y,w,h)清空矩形區域(透明)無(直接操作像素緩衝區)擦除、動畫幀清屏、裁剪遮罩

基礎示例


<canvas id="c" width="300" height="200"></canvas>
<script>
const ctx = document.getElementById('c').getContext('2d');

// 樣式設置
ctx.fillStyle = '#000';      // 黑色填充
ctx.strokeStyle = '#f0f';    // 紫色描邊
ctx.lineWidth = 2;

// 1. 填充矩形 (10,10) 40×40
ctx.fillRect(10, 10, 40, 40);

// 2. 描邊矩形 (0,0) 60×60
ctx.strokeRect(0, 0, 60, 60);

// 3. 清除矩形 (20,20) 20×20 - 在填充矩形中間挖洞
ctx.clearRect(20, 20, 20, 20);
</script>

效果:黑色實心方塊,外層紫色邊框,中心挖空 20×20 透明區域。

進階組合技巧

1. 圖層疊加順序


// 先畫背景大矩形
ctx.fillStyle = '#eee';
ctx.fillRect(0, 0, 300, 200);

// 再畫前景元素
ctx.fillStyle = 'red';
ctx.fillRect(50, 50, 100, 100);

// 最後描邊框
ctx.strokeStyle = 'blue';
ctx.lineWidth = 4;
ctx.strokeRect(48, 48, 104, 104);

2. 矩形裁剪區域


ctx.beginPath();
ctx.rect(50, 50, 200, 100);
ctx.clip(); // 後續繪製僅在矩形內可見

// 繪製大圖片,僅顯示矩形區域
ctx.drawImage(largeImage, 0, 0);

3. 橡皮擦效果


canvas.addEventListener('mousemove', e => {
  if (e.buttons & 1) { // 按住左鍵
    const rect = canvas.getBoundingClientRect();
    ctx.clearRect(e.clientX - rect.left - 10, e.clientY - rect.top - 10, 20, 20);
  }
});

4. 網格線批量繪製


function drawGrid(ctx, width, height, step, color = '#eee') {
  ctx.save();
  ctx.strokeStyle = color;
  ctx.lineWidth = 1;
  ctx.beginPath();
  for (let x = 0; x <= width; x += step) {
    ctx.moveTo(x, 0); ctx.lineTo(x, height);
  }
  for (let y = 0; y <= height; y += step) {
    ctx.moveTo(0, y); ctx.lineTo(width, y);
  }
  ctx.stroke();
  ctx.restore();
}

路徑模式 vs 直接方法

除三大直接方法外,也可用路徑繪製矩形:


// 路徑模式(可組合其他路徑、應用裁剪、非零環繞規則)
ctx.beginPath();
ctx.rect(10, 10, 100, 100); // 添加矩形路徑
ctx.rect(120, 10, 100, 100); // 可添加多個
ctx.fillStyle = 'red';
ctx.fill(); // 同時填充所有路徑

// 直接方法(立即繪製、性能略高、無法組合)
ctx.fillRect(10, 10, 100, 100);
ctx.fillRect(120, 10, 100, 100);

高清屏適配:devicePixelRatio


function setupHiDPI(canvas) {
  const dpr = window.devicePixelRatio || 1;
  const rect = canvas.getBoundingClientRect();
  canvas.width = rect.width * dpr;
  canvas.height = rect.height * dpr;
  canvas.style.width = rect.width + 'px';
  canvas.style.height = rect.height + 'px';
  const ctx = canvas.getContext('2d');
  ctx.scale(dpr, dpr);
  return ctx;
}

// 使用
const ctx = setupHiDPI(document.getElementById('c'));
ctx.fillRect(10, 10, 100, 100); // 邏輯坐標 100×100,實際物理像素 200×200 (dpr=2)

常見錯誤

  • 混淆 fillRect 與 rect()+fill():前者立即繪製,後者需配合路徑
  • clearRect 不會重置變換矩陣,若有 scale/rotate 需配合 save/restore 或 resetTransform()
  • 忘記設置 fillStyle/strokeStyle 導致使用上一次值(狀態機特性)
  • 負數 width/height:規範允許但行為不一致,避免使用

擴展:圓角矩形現代 API


// Chrome 107+, Firefox 105+, Safari 16.4+
ctx.roundRect(x, y, w, h, radius); // radius 可為數字或 [tl, tr, br, bl] 數組
ctx.fill(); // 或 stroke()

// 兼容性方案:Path2D + arcTo 封裝
const RoundRect = (x,y,w,h,r) => {
  const p = new Path2D();
  const rArr = Array.isArray(r) ? r : [r,r,r,r];
  p.moveTo(x+rArr[0], y);
  p.lineTo(x+w-rArr[1], y);
  p.arcTo(x+w, y, x+w, y+h, rArr[1]);
  p.lineTo(x+w, y+h-rArr[2]);
  p.arcTo(x+w, y+h, x, y+h, rArr[2]);
  p.lineTo(x+rArr[3], y+h);
  p.arcTo(x, y+h, x, y, rArr[3]);
  p.lineTo(x, y+rArr[0]);
  p.arcTo(x, y, x+w, y, rArr[0]);
  p.closePath();
  return p;
};
ctx.fill(RoundRect(10,10,100,100, [10,20,30,40]));

矩形三大方法是 Canvas 繪圖的基石。理解它們與樣式屬性的綁定關係、直接方法與路徑模式的差異、高清屏適配模式,能讓你在遊戲渲染、圖表繪製、圖像編輯、動畫幀清屏等場景下寫出高性能、無 Bug 的代碼。

copyright © 萬盛學電腦網 all rights reserved