簡介
HiDPI 螢幕非常出色,能讓所有內容看起來更流暢、更清晰。但同時也為開發人員帶來新的挑戰。本文將探討在 HiDPI 螢幕上,在畫布中繪製圖片時面臨的獨特挑戰。
devicePixelRatio 屬性
我們先從頭開始。在 HiDPI 螢幕問世前,像素就是像素 (如果我們暫時忽略縮放和縮放),您不需要變更任何內容。如果將某個項目的寬度設為 100 像素,就只能是這個寬度。接著,第一批 HiDPI 行動裝置開始出現,在視窗物件上提供稍微神秘的 devicePixelRatio 屬性,並可在媒體查詢中使用。這項屬性可讓我們瞭解 CSS 中的像素值 (我們稱為邏輯像素值) 與裝置在算繪時使用的實際像素數之間的比例。以 iPhone 4S 為例,其 devicePixelRatio 為 2,因此 100 像素的邏輯值相當於 200 像素的裝置值。
這很有趣,但對開發人員來說有什麼意義?在早期,我們都開始注意到這些裝置會放大圖片。我們以元素的邏輯像素寬度建立圖片,繪製時,圖片會依 devicePixelRatio 放大,因此會模糊不清。
實際的解決方法是建立由 devicePixelRatio 縮放的圖片,然後使用 CSS 將圖片縮小相同的量,畫布也一樣!
function setupCanvas(canvas) {
// Get the device pixel ratio, falling back to 1.
var dpr = window.devicePixelRatio || 1;
// Get the size of the canvas in CSS pixels.
var rect = canvas.getBoundingClientRect();
// Give the canvas pixel dimensions of their CSS
// size * the device pixel ratio.
canvas.width = rect.width * dpr;
canvas.height = rect.height * dpr;
var ctx = canvas.getContext('2d');
// Scale all drawing operations by the dpr, so you
// don't have to worry about the difference.
ctx.scale(dpr, dpr);
return ctx;
}
// Now this line will be the same size on the page
// but will look sharper on high-DPI devices!
var ctx = setupCanvas(document.querySelector('.my-canvas'));
ctx.lineWidth = 5;
ctx.beginPath();
ctx.moveTo(100, 100);
ctx.lineTo(200, 200);
ctx.stroke();