在使用 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
修改後邊框四側粗細、顏色完全一致,問題解決。
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
});
// 獲取裝置像素比
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.roundlineWidth 為整數 (或 0.5, 1.5 等半像素對齊情況)translate 位移量為整數canvas.width/height 並 context.scale(dpr, dpr)ctx.imageSmoothingEnabled = false 像素風格繪圖時關閉平滑