iOS Safari canvas goes blank: total canvas memory use exceeds the limit
Pages in our in-browser PDF viewer turned blank on iPhones after a few minutes of scrolling. iOS Safari caps the total memory of all canvases, and we never released the ones for pages off screen. Pooling and zeroing canvases fixed it.
Our contract review app renders PDFs in the browser with pdf.js, one <canvas> per page. On desktop it was fine. On iPhones, after scrolling through 30 or 40 pages of a long contract, new pages appeared as empty white rectangles. Scrolling back up, some of the earlier pages had gone blank too. Connecting the phone to a Mac and opening Web Inspector showed a warning repeated many times:
Total canvas memory use exceeds the maximum limit (384 MB).
On an older iPad the limit printed in the message was lower. In one case, when a user zoomed in hard, we also saw:
Canvas area exceeds the maximum limit (width * height > 16777216).
Reproducing it
Open a 120-page PDF in the viewer on an iPhone.
Scroll steadily to page 60 without stopping.
Pages after roughly 40 render blank; the warning appears in Web Inspector.
The page count where it breaks depends on device and zoom level: higher device pixel ratios mean bigger backing stores.
What we ruled out
pdf.js rendering errors. The render promises resolved without errors. pdf.js drew into canvases that Safari then refused to back with memory.
Overall tab memory. The tab was not killed and the page stayed responsive. The failure was specific to canvases.
WebGL. We use 2D contexts only.
Fonts and images inside the PDF. Simple text-only PDFs failed at the same page count, which pointed at canvas size rather than content.
Root cause
WebKit on iOS limits the total memory used by all canvas backing stores in a page, and separately limits the area of a single canvas. Our viewer created a new full-resolution canvas for every page as the user scrolled and never released them. Each iPhone page at device pixel ratio 3 used about 11 MB, so a few dozen pages crossed the total. Removing the elements from the DOM was not enough: the backing stores stayed allocated until garbage collection, which ran late.
What is happening under the hood
A 2D canvas has a backing store of width x height x 4 bytes. A page rendered at 1170 by 1650 device pixels for an iPhone's 3x screen needs about 7.7 MB, and pdf.js may allocate extra canvases while rendering. Desktop browsers mostly let canvases use as much memory as the system gives them. iOS Safari enforces two caps to protect a memory-constrained device:
Maximum canvas area: 16,777,216 pixels, which is 4096 x 4096. Bigger canvases fail to allocate.
Total canvas memory: a per-page budget that depends on the device's RAM. When exceeded, further canvases get no backing store and render blank.
When you remove a canvas from the DOM, its memory is released only when the element is garbage collected. If anything still references it (a cache, a closure, a pdf.js render task), it may never be. Shrinking the canvas to zero size forces the backing store to be freed immediately.
Environment
Component | Version / value |
|---|---|
Devices | iPhone 13, iPhone 15, iPad (9th generation) |
OS | iOS 26.1, iPadOS 26.1 |
Browser | Safari 26.1; Chrome for iOS (same WebKit engine) |
Renderer | pdf.js 5.x, 2D canvas per page |
App | React 19, virtualised list of pages |
Device pixel ratio | 3 on iPhones, 2 on iPad |
Minimal reproduction
// Allocates a full-size canvas per page and keeps every one alive.
const cache = new Map();
async function renderPage(pdf, n, container) {
const page = await pdf.getPage(n);
const viewport = page.getViewport({ scale: devicePixelRatio * 1.5 });
const canvas = document.createElement('canvas');
canvas.width = viewport.width;
canvas.height = viewport.height;
container.appendChild(canvas);
await page.render({ canvasContext: canvas.getContext('2d'), viewport }).promise;
cache.set(n, canvas); // never evicted
}
Who is affected
PDF viewers, image editors, map tiles, charting dashboards and games that create many canvases.
All browsers on iOS and iPadOS, because they share WebKit. macOS Safari has higher limits and rarely hits them.
Apps that render at
devicePixelRatiotimes an extra zoom factor without a ceiling.
The fix
Three changes: render only pages near the viewport, release canvases explicitly, and cap the backing store size.
1. Pool and release canvases. We keep at most a fixed number of live canvases, reuse them, and zero the ones we drop:
const MAX_LIVE = 6;
const live = new Map<number, HTMLCanvasElement>();
export function releaseCanvas(canvas: HTMLCanvasElement) {
canvas.width = 0; // frees the backing store now, not at GC time
canvas.height = 0;
canvas.remove();
}
export function evictFarPages(current: number) {
for (const [n, canvas] of live) {
if (Math.abs(n - current) > MAX_LIVE / 2) {
releaseCanvas(canvas);
live.delete(n);
}
}
}
2. Cancel in-flight renders before releasing, so pdf.js does not keep a reference:
const tasks = new Map<number, { cancel(): void }>();
function stopPage(n: number) {
tasks.get(n)?.cancel();
tasks.delete(n);
}
3. Cap the backing store. We limit the scale so no canvas passes 16.7 million pixels, and we use a lower ceiling on iOS to leave headroom for the total budget:
-const viewport = page.getViewport({ scale: devicePixelRatio * 1.5 });
+const MAX_PIXELS = isAppleMobile() ? 8_000_000 : 16_000_000;
+let scale = devicePixelRatio * zoom;
+const base = page.getViewport({ scale: 1 });
+const pixels = base.width * base.height * scale * scale;
+if (pixels > MAX_PIXELS) scale *= Math.sqrt(MAX_PIXELS / pixels);
+const viewport = page.getViewport({ scale });
When the user zooms past that ceiling, we render only the visible region of the page into a viewport-sized canvas instead of the whole page at huge resolution.
The cache map from the old code was removed. Pages far from the viewport are re-rendered when the user scrolls back, which takes about 80 ms per page on an iPhone 13 and is barely visible.
Alternatives and trade-offs
Render to images. Draw each page once, convert to a blob URL with
canvas.toBlob(), show it in an<img>, and release the canvas. Images are decoded and evicted by the browser more gracefully, at the cost of the encode step.Lower DPR on iOS only. Rendering at 2x on 3x screens cuts memory by more than half with a small sharpness loss on text. A reasonable emergency fix.
Server-side page images. Pre-render pages to WebP at fixed sizes. Removes the client limit but adds storage and loses text selection unless you overlay a text layer.
How to test the fix
On a real device (the simulator does not enforce the same memory limits):
Open the 120-page fixture PDF, scroll to the end and back twice.
Watch Web Inspector's console: no canvas memory warnings.
In Web Inspector, the Graphics tab lists live canvases and their memory; the count must stay at or below
MAX_LIVEplus the pdf.js scratch canvas.
We also added a debug overlay in staging that shows live canvas count and estimated bytes:
const bytes = [...live.values()].reduce((s, c) => s + c.width * c.height * 4, 0);
overlay.textContent = `canvases ${live.size}, ~${(bytes / 1e6).toFixed(0)} MB`;
Confirming in production
We log a viewer_blank_page event when a rendered canvas reads back fully transparent in a sampled pixel check, plus total live canvas bytes at intervals:
viewer_blank_page{os="iOS"} before: ~2,300/week after: 4/week
viewer_live_canvas_mb_p95{os="iOS"} before: 610 after: 58
The remaining blank-page events came from a corrupt PDF and are unrelated.
Regression guard
A Playwright WebKit test scrolls the long fixture and asserts the live canvas count never exceeds the pool size, read from the debug hook.
Code review rule: any new
document.createElement('canvas')must go through the pool helper.A unit test for the scale cap feeds a giant page and asserts the computed area stays under the ceiling.
Security implications
None beyond availability. Unbounded canvas allocation can be used to make a page unusable on mobile, so the caps also protect against hostile documents with enormous page sizes: we already validate PDF page dimensions server-side and now clamp them client-side too. Releasing canvases does not leak content; zeroing the size clears the bitmap.
Prevention checklist
Virtualise: render only what is near the viewport.
Release canvases by setting
widthandheightto 0 before dropping them.Cap each canvas below 16,777,216 pixels and budget for the total on iOS.
Cancel pending render tasks before releasing their canvases.
Test long sessions on a real iPhone, not only desktop Safari.
References
MDN, Canvas element maximum size: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas#maximum_canvas_size
MDN, Optimizing canvas: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Optimizing_canvas
Apple, Inspecting iOS and iPadOS with Web Inspector: https://developer.apple.com/documentation/safari-developer-tools/inspecting-ios
WebKit, Web Inspector Graphics tab: https://webkit.org/web-inspector/
pdf.js API documentation: https://mozilla.github.io/pdf.js/api/
Add a label
Embed this post
<iframe src="https://hibug.me/ios-safari-canvas-blank-total-canvas-memory-limit" width="700" height="420" frameborder="0" loading="lazy"></iframe>
I work on databases and data pipelines: MySQL and PostgreSQL in production, Kafka streams, change data capture and the analytical stores downstream. I started as a backend developer on a gaming platform, where a single race condition could hand out items that did not exist, and that taught me to respect concurrency early. Most of my posts start with an alert: a disk filling overnight, a server at full CPU, missing rows after a failover. I show how we traced it to the root cause, the fix, and the monitoring or test we added so it does not happen twice.
Comments
0No comments yet. Be the first to comment!
Sign In to post a comment.