萬盛學電腦網

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

HTML5 Canvas 繪製矩形邊框樣式不一致問題解決:座標必須為整數

在使用 Canvas rect(x, y, w, h) 繪製矩形時,若座標或尺寸包含非整數(浮點數),會導致邊框粗細不均、顏色深淺不一(子像素渲染模糊)。解決方法極簡單:所有座標與尺寸取整(Math.round/Math.floor/|0)。

問題重現

<canvas id="myCanvas" width="578" height="200"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');

context.beginPath();
context.rect(188.0, 50, 200, 100.375);  // 含浮點數
context.fillStyle = 'white';
context.fill();
context.lineWidth = 1;
context.strokeStyle = 'red';
context.stroke();
</script>
邊框不一致示意圖:底部明顯較細、顏色較淡
底部邊框明顯較細、顏色較淡 — 典型子像素渲染異常

解決方案:座標取整

// 修改前
context.rect(188.0, 50, 200, 100.375);

// 修改後:全部取整
context.rect(188, 50, 200, 100);  // 或 Math.round(100.375) → 100
修改後邊框四側粗細、顏色完全一致,問題解決。

根本原因:子像素渲染

  • Canvas 坐標系統基於設備像素,但允許浮點數座標。
  • 當座標落在像素邊界之間(如 100.375),瀏覽器執行反鋸齒/子像素渲染,將線條強度分配給相鄰像素。
  • 導致邊框實際覆蓋 1.5~2 個像素寬度,視覺上出現粗細不均、顏色變淡。
  • lineWidth: 1 時最明顯;較粗線條 (>=2) 影響較小但仍存在。

最佳實務:繪圖前統一取整

function drawRect(ctx, x, y, w, h, style) {
  // 強制取整,避免子像素問題
  x = Math.round(x);
  y = Math.round(y);
  w = Math.round(w);
  h = Math.round(h);
  
  ctx.beginPath();
  ctx.rect(x, y, w, h);
  if (style.fill) {
    ctx.fillStyle = style.fill;
    ctx.fill();
  }
  if (style.stroke) {
    ctx.lineWidth = style.width || 1;
    ctx.strokeStyle = style.stroke;
    ctx.stroke();
  }
}

// 使用
drawRect(context, 188.3, 50.7, 200.2, 100.6, {
  fill: 'white',
  stroke: 'red',
  width: 1
});

延伸:高解析度螢幕 (Retina/High-DPI) 處理

// 獲取裝置像素比
var dpr = window.devicePixelRatio || 1;

// 設定畫布實際像素尺寸 = CSS 尺寸 * dpr
canvas.width = 578 * dpr;
canvas.height = 200 * dpr;
canvas.style.width = '578px';
canvas.style.height = '200px';

// 縮放繪圖上下文
context.scale(dpr, dpr);

// 之後所有座標按 CSS 像素計算,再取整即可
context.rect(Math.round(188), Math.round(50), Math.round(200), Math.round(100));
高 DPI 處理核心:Canvas 位圖尺寸 × dpr,CSS 顯示尺寸不變,Context 縮放 dpr,繪圖座標仍用 CSS 像素並取整。

快速檢查清單

  • [ ] 所有 rect/moveTo/lineTo/arc 座標經過 Math.round
  • [ ] lineWidth 為整數 (或 0.5, 1.5 等半像素對齊情況)
  • [ ] translate 位移量為整數
  • [ ] 高 DPI 環境已設定 canvas.width/height 並 context.scale(dpr, dpr)
  • [ ] 使用 ctx.imageSmoothingEnabled = false 像素風格繪圖時關閉平滑
copyright © 萬盛學電腦網 all rights reserved