HTML Canvas 畫圖模糊?用 devicePixelRatio 對齊像素
本文目錄
HTML Canvas 的 CSS 寬高決定畫面上佔多少空間,canvas.width 和 canvas.height 則決定 2D 畫布有多少像素。當一張 300 × 150 的畫布顯示成 300 × 150 CSS 像素,而 devicePixelRatio 是 2,畫布就會被放大到約 600 × 300 個裝置像素。可以擴充點陣圖的像素數,再用 setTransform() 讓繪圖指令繼續使用 CSS 座標。
量出 Canvas 的兩組尺寸
在頁面用開發者工具選取 <canvas>,比較 $0.getBoundingClientRect() 和 [$0.width, $0.height]。前者含邊框與內距,量測前要扣除這些尺寸,或像下方範例一樣把外框樣式都放在容器。若一畫就模糊,先看像素數夠不夠。若是改變尺寸後畫面空白,則先查程式有沒有在改寬高之後重畫。
調整畫布像素數後,用相同座標重繪
範例請存成 HTML 開啟。按下按鈕可切換畫布寬度,觀察下方的 CSS 寬高與點陣圖寬高。外層提供尺寸,因此 JavaScript 改畫布像素數時,畫布在版面上的寬度由 CSS 繼續控制。
<!doctype html><meta charset="utf-8"><title>Canvas 清晰度檢查</title><style> #frame { width: min(100%, 300px); } #frame.narrow { width: min(100%, 200px); } canvas { display: block; width: 100%; height: 120px; }</style>
<button id="toggle" type="button">切換寬度</button><div id="frame"> <canvas id="chart">斜線和像素密度的示意圖</canvas></div><output id="size"></output>
<script> const frame = document.querySelector('#frame'); const canvas = document.querySelector('#chart'); const size = document.querySelector('#size'); const ctx = canvas.getContext('2d');
function render() { const { width, height } = canvas.getBoundingClientRect(); if (width === 0 || height === 0) return;
const dpr = window.devicePixelRatio || 1; const pixelWidth = Math.max(1, Math.round(width * dpr)); const pixelHeight = Math.max(1, Math.round(height * dpr));
if (canvas.width !== pixelWidth) canvas.width = pixelWidth; if (canvas.height !== pixelHeight) canvas.height = pixelHeight;
ctx.setTransform(pixelWidth / width, 0, 0, pixelHeight / height, 0, 0); ctx.clearRect(0, 0, width, height); ctx.strokeStyle = '#0f766e'; ctx.lineWidth = 2; ctx.beginPath(); ctx.moveTo(16, height - 16); ctx.lineTo(width - 16, 16); ctx.stroke();
size.value = `CSS ${width} × ${height};點陣圖 ${pixelWidth} × ${pixelHeight};DPR ${dpr}`; }
new ResizeObserver(render).observe(canvas); window.addEventListener('resize', render); document.querySelector('#toggle').addEventListener('click', () => { frame.classList.toggle('narrow'); }); render();</script>在 DPR 2、容器有足夠空間時,讀值應從 CSS 300 × 120、點陣圖 600 × 240,切換成 CSS 200 × 120、點陣圖 400 × 240。斜線仍維持 2 CSS 像素寬。setTransform() 每次替換轉換矩陣,因此連續重繪也能沿用同一組座標。設定 width 或 height 會清除畫面及重設 2D context 狀態,所以範例在確認尺寸後才設定筆畫與繪圖。
ResizeObserver 在畫布的 CSS 尺寸變動時觸發,例如容器隨側欄縮窄。如果應用程式會在不同像素密度的螢幕之間移動,還要驗證畫布的 CSS 尺寸維持原樣時,DPR 變動有沒有觸發重繪。需要監聽這種情況,可以用目前 DPR 組成 (resolution: 2dppx) 之類的媒體查詢,在 change 時重繪並依新值重新註冊。
若尺寸已匹配,模糊只出現在使用 drawImage() 的區塊,接著檢查來源圖本身有多少像素。加大畫布可以保留繪圖細節,低解析度的來源圖仍有自己的解析度上限。
參考資料: