Canvas Scales With devicePixelRatio
Multiplying the canvas backing store by window.devicePixelRatio and scaling the context keeps lines crisp on high-DPI displays.
Code
// 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,windowexist only in browsers — a Node runtime has no shims for them out of the box.- The guard
!ctxexits the current step right away with an earlythrowwhen 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
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.