<canvas id="canvas"></canvas>Window: devicePixelRatio property / notebook
Window: devicePixelRatio property
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
// Set display size (css pixels).
const size = 200;
canvas.style.width = `${size}px`;
canvas.style.height = `${size}px`;
// Set actual size in memory (scaled to account for extra pixel density).
const 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);
ctx.fillStyle = "#bada55";
ctx.fillRect(10, 10, 300, 300);
ctx.fillStyle = "white";
ctx.font = "18px Arial";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
const x = size / 2;
const y = size / 2;
const textString = "I love MDN";
ctx.fillText(textString, x, y);<div id="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
<code>devicePixelRatio</code> property.
</p>
<p>Try it and watch what happens!</p>
</div>
<div id="output"></div>body {
font:
22px "Arial",
sans-serif;
}
#container {
border: 2px solid #2222dd;
margin: 1rem auto;
padding: 1rem;
background-color: #aa99ff;
}let remove = null;
const output = document.querySelector("#output");
const updatePixelRatio = () => {
remove?.();
const mqString = `(resolution: ${window.devicePixelRatio}dppx)`;
const media = matchMedia(mqString);
media.addEventListener("change", updatePixelRatio);
remove = () => {
media.removeEventListener("change", updatePixelRatio);
};
output.textContent = `devicePixelRatio: ${window.devicePixelRatio}`;
};
updatePixelRatio();