使用 Canvas 繪製矩形時,若 width 或 height 帶有小數,可能會讓邊框看起來粗細不一、顏色略差,甚至出現模糊。這通常是因為座標落在半像素或子像素位置,觸發抗鋸齒。
context.rect(188.0, 50, 200, 100.375);
context.fillStyle = 'white';
context.fill();
context.lineWidth = 1;
context.strokeStyle = 'red';
context.stroke();執行後可看到底部邊框較細,顏色也可能與其他邊不同。

將參數取整數,讓矩形對齊像素網格:
context.rect(188.0, 50, 200, 100);修改後邊框粗細與顏色就會一致。