mozilla/pdf.js · error · Error

Invalid canvas size

Error message

Invalid canvas size

What it means

Thrown by BaseCanvasFactory.create(width, height) when width or height is <= 0. Canvases must have positive integer pixel dimensions; zero or negative sizes are meaningless and would produce invalid buffer allocation in the platform's canvas backend. PDF.js validates up front to fail fast.

Source

Thrown at src/display/canvas_factory.js:33

import { unreachable } from "../shared/util.js";

class BaseCanvasFactory {
  #enableHWA = false;

  constructor({ enableHWA = false }) {
    if (
      (typeof PDFJSDev === "undefined" || PDFJSDev.test("TESTING")) &&
      this.constructor === BaseCanvasFactory
    ) {
      unreachable("Cannot initialize BaseCanvasFactory.");
    }
    this.#enableHWA = enableHWA;
  }

  create(width, height) {
    if (width <= 0 || height <= 0) {
      throw new Error("Invalid canvas size");
    }
    const canvas = this._createCanvas(width, height);
    return {
      canvas,
      context: canvas.getContext("2d", {
        willReadFrequently: !this.#enableHWA,
      }),
    };
  }

  reset({ canvas }, width, height) {
    if (!canvas) {
      throw new Error("Canvas is not specified");
    }
    if (width <= 0 || height <= 0) {
      throw new Error("Invalid canvas size");
    }
    canvas.width = width;

View on GitHub (pinned to 5903d58d58)

Solutions

  1. Clamp width/height to at least 1: Math.max(1, Math.round(viewport.width)).
  2. Skip the render entirely when the page is not visible (size 0) instead of calling create.
  3. Validate viewport scale before computing canvas size.

Example fix

// before
const { canvas, context } = canvasFactory.create(viewport.width, viewport.height);

// after
const w = Math.max(1, Math.round(viewport.width));
const h = Math.max(1, Math.round(viewport.height));
const { canvas, context } = canvasFactory.create(w, h);
Defensive patterns

Strategy: validation

Validate before calling

function safeCreate(factory, w, h) {
  w = Math.max(1, Math.round(w));
  h = Math.max(1, Math.round(h));
  return factory.create(w, h);
}

Type guard

const isPositiveSize = (n): n is number => Number.isFinite(n) && n > 0;

Try / catch

null

Prevention

When it happens

Trigger: Calling canvasFactory.create(0, 100), create(-10, 50), or create(NaN, 100) (NaN <= 0 is false but create with NaN propagates downstream — the strict check catches the explicit zero/negative cases). Triggered when viewport dimensions round to zero at extreme zoom-out or for an empty page.

Common situations: Rendering at a scale where width/height compute to 0 (very small zoom); passing CSS pixel values that floored to 0; tests with placeholder dimensions.

Related errors


AI-assisted analysis of mozilla/pdf.js@5903d58d58 (2026-08-13). Data as JSON: /api/errors/d8f59fb07b5f0054. Report an issue: GitHub.