A user clicks zoom twice, and the PDF page disappears. The console reports that the same canvas is already in use by another render operation. A viewer can hit this when a new zoom, rotation, or page selection starts drawing before the previous PDF.js render has finished.
The tricky part is that cancel() starts cancellation; it does not make every asynchronous step in your viewer disappear. You still need to wait for the render task's promise to settle before reusing that canvas. You also need to ignore older page requests that finish loading after a newer request has arrived.
A race with two different clocks
Suppose the user selects page 3, then immediately selects page 4. Both getPage() calls run asynchronously. Page 4 can become available first, while the older page 3 request is still pending. If the older request starts a render when it eventually returns, the canvas can show the wrong page or collide with a render already in progress.
Zoom creates the same problem even if the page number stays fixed. Each request has a different viewport, and resetting the canvas dimensions while an earlier task is drawing can corrupt the result. A boolean such as isRendering alone does not tell you which of several pending requests is the latest.
A PDF.js maintainer described cancellation as asynchronous in issue #9456. The project's subsequent fix and regression test also show a render being cancelled, its promise settling, and the canvas being reused. That issue concerned an older PDF.js version; it is useful evidence for the lifecycle, not a claim that its specific bug still exists today.
Serialize work for one canvas
The following controller owns one canvas. It cancels the active render as soon as a new request arrives, serializes access to the canvas, and uses a generation number to discard requests that became stale while waiting. It assumes pdf is an already loaded PDF.js document and that the canvas has a 2D context.
function makePageRenderer(pdf, canvas) {
let generation = 0;
let active = null;
let queue = Promise.resolve();
function show(pageNumber, scale) {
const request = ++generation;
if (active) active.cancel();
const work = queue.then(async () => {
if (request !== generation) return;
const page = await pdf.getPage(pageNumber);
if (request !== generation) return;
const viewport = page.getViewport({ scale });
canvas.width = Math.ceil(viewport.width);
canvas.height = Math.ceil(viewport.height);
const task = page.render({
canvasContext: canvas.getContext('2d'),
viewport,
});
active = task;
try {
await task.promise;
} catch (error) {
if (error.name !== 'RenderingCancelledException') throw error;
} finally {
if (active === task) active = null;
}
});
// Keep the queue usable after a failure; the caller still receives it.
queue = work.catch(() => {});
return work;
}
return { show };
}
Call show(3, 1.5) on a page or zoom change, and attach an error handler to the returned promise. Each invocation advances the generation immediately. A queued request checks its generation both before and after getPage(), so an older page load cannot start drawing after a newer selection. When an active render is cancelled, the queue waits for that task's promise before the next request can resize or render into the canvas.
The empty catch belongs only to the internal queue tail: it lets later requests run even if one failed. The returned work promise still rejects for unexpected errors. Surface those errors in the UI or logs instead of treating all failures as normal cancellation.
Test the lifecycle, not just the final page
Use a multi-page PDF and rapidly alternate page numbers and zoom levels. The last selection should be the one displayed. Watch for unhandled promise rejections and same-canvas errors, and repeat with a deliberately slow page load so that an older getPage() resolves after a newer selection.
Also test leaving the viewer while work is pending. A component should invalidate pending requests and cancel its active task during teardown; wait for that task to settle before destroying or reusing its canvas. If the application can switch documents, give the new document its own controller and retire the old one before handing over the canvas.
This example uses one bitmap pixel per viewport unit for clarity. A production viewer may use a device-pixel-ratio transform for sharper output, subject to a canvas memory budget. Text and annotation layers need their own lifecycle and should be updated only for the current request as well. Keeping those layers in sync matters: a sharp bitmap with stale selectable text or misplaced form controls is still the wrong page.
For the related coordinate problem, see why PDF annotations move when you rotate or zoom a page.
Top comments (0)