Canvas Scales With devicePixelRatio

Multiplying the canvas backing store by window.devicePixelRatio and scaling the context keeps lines crisp on high-DPI displays.

JavascriptData Integrity

Code

javascriptsnippet
24 lines
// A canvas sized only in CSS pixels renders blurry on high-DPI displays;
// devicePixelRatio scales the backing store to match the screen
const canvas = document.querySelector('#chart');
const dpr = window.devicePixelRatio || 1;

const cssWidth = canvas.clientWidth;
const cssHeight = 160;

canvas.width = Math.round(cssWidth * dpr);
canvas.height = Math.round(cssHeight * dpr);
canvas.style.height = `${cssHeight}px`;

const ctx = canvas.getContext('2d');
if (!ctx) throw new Error('2d context unavailable');

ctx.scale(dpr, dpr);
ctx.lineWidth = 1 / dpr; // hairlines stay crisp after scaling

ctx.beginPath();
ctx.moveTo(10, 80);
ctx.lineTo(120, 80);
ctx.stroke();

console.log('backing store:', canvas.width, 'x', canvas.height, 'dpr:', dpr);

How the snippet works

Invalid states are rejected up front: it throws Error instead of continuing with bad data.

The file’s state is a handful of top-level bindings: canvas, dpr, cssWidth, cssHeight.

Watch out for

  • The environment needs no preparation beyond having the interpreter or compiler.
  • document, window exist only in browsers — a Node runtime has no shims for them out of the box.
  • The guard !ctx exits the current step right away with an early throw when its condition holds.

Applying it

The run emits 1 labeled section — backing store: — one per step.

Statements that carry the weight

if (!ctx) throw new Error('2d context unavailable');

Interactive Tools for This Topic

FAQ

How does the code behave when input is bad?
Validation comes first — `Error` marks the failure at `!ctx`, before any partial work happens.
Does Canvas Scales With devicePixelRatio run in plain Node.js?
No — it touches `document` and `window`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.