<canvas>可能在视网膜屏幕上显得太模糊。 使用window.devicePixelRatio确定应添加多少额外的像素密度以使图像更清晰。 HTML
<canvas id="canvas"></canvas>
JavaScript
var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d');
// Set display size (css pixels). var size = 200; canvas.style.width = size + "px"; canvas.style.height = size + "px";
// Set actual size in memory (scaled to account for extra pixel density). var scale = window.devicePixelRatio; // Change to 1 on retina screens to see blurry canvas. canvas.width = Math.floor(size * scale); canvas.height = Math.floor(size * scale);
// Normalize coordinate system to use css pixels. ctx.scale(scale, scale);
然后,调用updatePixelRatio()函数一次以显示起始值,然后使用matchMedia() 和 addEventListener()来将updatePixelRatio()设置为change事件的处理程序。 HTML
HTML 将创建包含说明的框和将显示当前像素比率信息的pixel-ratio 框。
<div class="container"> <div class="inner-container"> <p>This example demonstrates the effect of zooming the page in and out (or moving it to a screen with a different scaling factor) on the value of the property <code>Window.devicePixelRatio</code>. Try it and watch what happens!</p> </div> <div class="pixel-ratio"></div> </div>