Canvas looks blurry on Retina screens: fix it with devicePixelRatio
Our charts looked crisp on office monitors and fuzzy on every MacBook. The canvas backing store matched the CSS size, so the browser stretched it 2x. Scaling by devicePixelRatio and reacting to zoom and monitor changes fixed it.
Our analytics dashboard draws its main time-series chart on a <canvas> because SVG got slow past 50,000 points. The first complaint came from a designer: "the chart text looks like it went through a fax machine." On her MacBook, axis labels were soft and one-pixel grid lines looked two pixels wide and grey. On the office's 1080p monitors the same chart looked fine.
Then a second report: on a Windows laptop at 150 percent display scaling, the chart was sharp after a page reload but went blurry when the user dragged the browser onto an external monitor.
Reproducing it
<canvas id="chart" style="width: 600px; height: 300px"></canvas>
<script>
const canvas = document.getElementById('chart');
canvas.width = 600; // backing store = CSS size
canvas.height = 300;
const ctx = canvas.getContext('2d');
ctx.font = '12px system-ui';
ctx.fillText('Requests per second', 10, 20);
ctx.strokeRect(0.5, 40.5, 580, 240);
</script>
Open it on any screen where window.devicePixelRatio is 2 or more and compare the text with normal page text next to it.
What we ruled out
Font loading. The web font loaded before drawing; using
system-uilooked equally soft.CSS transforms. No
transform: scale()on parents, which can also blur canvases.Image smoothing.
imageSmoothingEnabledaffects drawing images onto the canvas, not how the canvas itself is displayed.Half-pixel offsets. We already drew lines at
.5coordinates for crisp one-pixel strokes. That only helps when one canvas pixel equals one screen pixel.
Root cause
A canvas has two sizes: the backing store (canvas.width and canvas.height, in canvas pixels) and the display size (CSS width and height, in CSS pixels). We set both to 600 by 300. On a screen with devicePixelRatio 2, 600 CSS pixels cover 1,200 physical pixels, so the browser upscaled our 600-pixel bitmap to fill them, like stretching a small image. The external-monitor case was the same problem appearing later: the ratio changed from 1.5 to 1 and our code never noticed.
What is happening under the hood
window.devicePixelRatio is the number of physical pixels per CSS pixel. It is 2 on most Macs, 3 on many phones, often 1.25 or 1.5 on Windows laptops with display scaling, and it changes with browser zoom: zooming to 200 percent on a 1x monitor makes it 2.
SVG and HTML text are vector: the browser redraws them at the right density automatically. A canvas is a bitmap you fill yourself, so you must allocate enough pixels for the screen and tell the drawing code to work in CSS units.
The standard recipe:
Backing store = CSS size times
devicePixelRatio, rounded.CSS size stays the same.
Scale the context by the ratio so your drawing code keeps using CSS coordinates.
Environment
Component | Version / value |
|---|---|
MacBook Pro | macOS Tahoe 26.1, built-in display, DPR 2 |
Windows laptop | Windows 11 24H2, 150% scaling (DPR 1.5) + 1080p external monitor (DPR 1) |
Browsers | Chrome 142, Firefox 145, Safari 26.1 |
App | React 19 dashboard, custom canvas chart, ~50k points |
Minimal reproduction
The snippet in Investigate is the full reproduction. To see the ratio and the mismatch:
console.log(devicePixelRatio); // 2 on a MacBook
console.log(canvas.width, canvas.clientWidth); // 600 600: needs 1200 600
Who is affected
Every canvas app that sets
widthandheightto the CSS size: charts, signature pads, editors, games with UI text.Users on high-DPI displays, users who zoom, and users who move windows between monitors.
WebGL canvases too: the same backing-store rule applies, and
gl.viewportmust match.
The fix
We wrapped canvas sizing in one function that runs on load, on resize and on ratio changes.
export function fitCanvas(canvas: HTMLCanvasElement, ctx: CanvasRenderingContext2D) {
const dpr = window.devicePixelRatio || 1;
const { width, height } = canvas.getBoundingClientRect(); // CSS pixels
const w = Math.round(width * dpr);
const h = Math.round(height * dpr);
if (canvas.width !== w || canvas.height !== h) {
canvas.width = w; // resizing also clears the canvas and resets the context state
canvas.height = h;
}
ctx.setTransform(dpr, 0, 0, dpr, 0, 0); // draw in CSS pixels from here on
return { width, height, dpr };
}
-canvas.width = 600;
-canvas.height = 300;
-const ctx = canvas.getContext('2d');
-drawChart(ctx, 600, 300);
+const ctx = canvas.getContext('2d')!;
+function redraw() {
+ const { width, height } = fitCanvas(canvas, ctx);
+ drawChart(ctx, width, height);
+}
+redraw();
We use setTransform rather than ctx.scale because scale multiplies the current transform, so calling it twice would double the scale.
Reacting to zoom and monitor changes
Resizing the window fires resize, but moving to a monitor with a different ratio may not change the CSS size at all. A media query on the current resolution fires when the ratio changes. It must be re-registered each time, because the query is built from the old value:
function watchDpr(onChange: () => void) {
const mq = matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`);
mq.addEventListener('change', () => {
onChange();
watchDpr(onChange); // new ratio, new query
}, { once: true });
}
new ResizeObserver(redraw).observe(canvas);
watchDpr(redraw);
Exact pixel sizes with devicePixelContentBoxSize
Multiplying and rounding can be off by one pixel at fractional ratios like 1.25, which makes thin lines shimmer. Chromium and Firefox report the exact device-pixel size through ResizeObserver. We use it when available and fall back to the rounded value:
new ResizeObserver(([entry]) => {
const box = entry.devicePixelContentBoxSize?.[0];
if (box) {
canvas.width = box.inlineSize;
canvas.height = box.blockSize;
}
redraw();
}).observe(canvas, { box: 'device-pixel-content-box' });
Safari does not support the device-pixel-content-box option at the time of writing, so check support and keep the fallback path.
Alternatives and trade-offs
Cap the ratio. On 3x phones with huge charts, a backing store of three times the CSS size in each direction costs nine times the memory. We cap at 2 on mobile; the difference is hard to see on a chart.
OffscreenCanvas in a worker. Same sizing rules, but the drawing work moves off the main thread. Worth it for heavy charts.
SVG for text, canvas for data. Draw axes and labels as HTML or SVG overlays and only the dense series on canvas. Text stays perfectly sharp with no canvas tricks.
How to test the fix
Open the dashboard on a Mac and zoom the browser to 200 percent: labels stay sharp.
On Windows, drag the window between the 150 percent laptop screen and the 100 percent monitor: the chart redraws sharp on both.
Playwright can emulate a ratio:
test.use({ deviceScaleFactor: 2 });
test('canvas backing store follows DPR', async ({ page }) => {
await page.goto('/dashboard');
const [w, cw] = await page.$eval('#chart', (c: HTMLCanvasElement) => [c.width, c.clientWidth]);
expect(w).toBe(cw * 2);
});
Confirming in production
We log the ratio and the backing-store size once per dashboard load and check they agree:
chart_backing_mismatch_rate before: 71% after: 0.1%
The leftover cases were browsers zoomed to non-integer levels where rounding differs by one pixel, which is harmless.
Regression guard
All canvases are created through a
useCanvashook that callsfitCanvasand wires the observers.The Playwright test above runs at scale factors 1, 2 and 3.
A screenshot test at 2x compares the chart against a baseline image with a small tolerance.
Security implications
None. The fix changes rendering density only. Very large ratios multiply memory use, so clamping the ratio (we cap at 3) also prevents an extreme zoom from allocating oversized canvases that could make the page unresponsive on low-memory devices.
Prevention checklist
Set the backing store to CSS size times
devicePixelRatio.Use
setTransform(dpr, 0, 0, dpr, 0, 0)so drawing code stays in CSS pixels.Redraw on resize and on ratio changes, re-registering the media query each time.
Cap the ratio on memory-constrained devices.
Test at 1x, 2x and 3x before release.
References
MDN, Window.devicePixelRatio: https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio
MDN, Optimizing canvas (scaling for high resolution displays): https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Optimizing_canvas
MDN, ResizeObserverEntry.devicePixelContentBoxSize: https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserverEntry/devicePixelContentBoxSize
MDN, CanvasRenderingContext2D.setTransform(): https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/setTransform
Playwright, emulation options: https://playwright.dev/docs/emulation
Add a label
Embed this post
<iframe src="https://hibug.me/canvas-blurry-on-retina-devicepixelratio" width="700" height="420" frameborder="0" loading="lazy"></iframe>
I build backend services in Go, Node.js and Python, mostly APIs and workers behind high-traffic products. Over the years I have become the person who gets the "it only fails under load" tickets. Those bugs are almost always about concurrency or resource limits: goroutines that never exit, a blocked event loop, a connection limit nobody knew existed. I write each one up with a small program that reproduces it, an explanation of the runtime behaviour behind it, the fix and the test or metric that proves it, so the next engineer does not need a load test to find it.
Comments
0No comments yet. Be the first to comment!
Sign In to post a comment.