CKTIS / JavaScript
Read and watch the device pixel ratio with `matchMedia()`
Read the number of device pixels per CSS pixel and use a resolution media query to detect when that ratio changes.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
window.devicePixelRatio // read-only number
window.matchMedia(mediaQueryString) // returns a new MediaQueryList
window.matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`)
window.matchMedia('(min-resolution: 2dppx)').matches // boolean
query.addEventListener('change', listener)
query.removeEventListener('change', listener)Window.devicePixelRatio/matchMedia pairs a read-only property with a method. window.devicePixelRatio gives the number of device pixels per CSS pixel, which can be fractional. Changing the browser’s page zoom or moving the window to a display with different scaling can change the ratio. Pinch zoom does not change it.
window.matchMedia() takes a CSS media query string and returns a new MediaQueryList. Read matches for the current result. The object fires change only when that boolean flips. For example, (min-resolution: 2dppx) tests for at least two device pixels per CSS pixel; a change from 2 to 3 does not cross that threshold.
To watch DPR changes, build an exact query (resolution: …dppx), replacing … with the current DPR. On change, remove the listener from the old object, read the new DPR, and attach the listener to a fresh query. If the exact query does not match initially, do not assume the next DPR change will trigger it. Remove the active listener when you no longer need the watcher.
These are browser Window APIs, not ECMAScript 2024 features or worker globals. Check support in your target browsers; addListener() and removeListener() are deprecated compatibility methods.
Examples
function watchDpr(viewport) {
let query;
function stop() {
query?.removeEventListener('change', update);
query = undefined;
}
function update() {
stop();
const dpr = viewport.devicePixelRatio;
query = viewport.matchMedia(`(resolution: ${dpr}dppx)`);
query.addEventListener('change', update);
console.log(`DPR: ${dpr}`);
}
update();
return stop;
}
// Node.js test fixture: models only exact-resolution media queries.
function createTestWindow(dpr) {
const queries = [];
return {
get devicePixelRatio() { return dpr; },
matchMedia(media) {
const [, value] = /^\(resolution: (.+)dppx\)$/.exec(media);
const resolution = Number(value);
const query = new EventTarget();
Object.defineProperty(query, 'matches', { get: () => dpr === resolution });
queries.push(query);
return query;
},
setDpr(nextDpr) {
// Snapshot the queries before listeners can create new ones.
const previous = queries.map(query => [query, query.matches]);
dpr = nextDpr;
for (const [query, matched] of previous) {
if (query.matches !== matched) {
query.dispatchEvent(new Event('change'));
}
}
},
};
}
const stopDprWatch = (() => {
if (typeof window !== 'undefined') return watchDpr(window);
const testWindow = createTestWindow(1);
const stop = watchDpr(testWindow);
testWindow.setDpr(2);
stop();
testWindow.setDpr(3); // The watcher should not log after cleanup.
return stop;
})();Result
DPR: 1 DPR: 2
In a browser console, the first line is logged immediately; further lines follow detected changes. Actual browser values may differ from those shown. Call `stopDprWatch()` to stop watching. In Node.js, a test fixture simulates a DPR change from 1 to 2, and the watcher stops before the simulated change to 3.
Related lessons
- JavaScript · Lesson 34 · Advanced · Version: 4