Stirling-Tools/Stirling-PDF · error · Error

Failed to get canvas context

Error message

Failed to get canvas context

What it means

Thrown inside resizeImageToMaxDimension after document.createElement("canvas").getContext("2d") returned null. A 2D context is null only when the browser cannot allocate a canvas backing store (memory exhaustion), when the page is running in a non-DOM/hostile context, or when an extension/policy blocks canvas rendering. The function then calls ctx.drawImage and canvas.toBlob, so without a context it cannot proceed.

Source

Thrown at frontend/editor/src/core/utils/imageToPdfUtils.ts:262

        }

        let newWidth: number;
        let newHeight: number;

        if (width > height) {
          newWidth = maxDimension;
          newHeight = (height / width) * maxDimension;
        } else {
          newHeight = maxDimension;
          newWidth = (width / height) * maxDimension;
        }

        const canvas = document.createElement("canvas");
        canvas.width = newWidth;
        canvas.height = newHeight;

        const ctx = canvas.getContext("2d");
        if (!ctx) throw new Error("Failed to get canvas context");
        ctx.drawImage(img, 0, 0, newWidth, newHeight);

        const outputType = imageFile.type.startsWith("image/")
          ? imageFile.type
          : "image/jpeg";

        canvas.toBlob(
          (blob) => {
            if (!blob) {
              reject(new Error("Failed to convert canvas to blob"));
              return;
            }
            const reducedFile = new File([blob], imageFile.name, {
              type: outputType,
            });
            URL.revokeObjectURL(url);
            resolve(reducedFile);
          },

View on GitHub (pinned to 9ef20dcab8)

Solutions

  1. Verify the failure is environmental by logging navigator.webdriver and document.createElement('canvas').getContext('2d') in the same context.
  2. Reduce the input image size before calling resize, or cap maxDimension lower to keep canvas backing-store within browser limits.
  3. In test environments, configure jsdom with the 'canvas' package or skip this code path.
  4. Detect a null context and surface a user-facing message instead of crashing the multi-tool workflow.

Example fix

// before
const ctx = canvas.getContext("2d");
if (!ctx) throw new Error("Failed to get canvas context");

// after
const ctx = canvas.getContext("2d");
if (!ctx) {
  throw new Error(
    "Failed to get canvas context: the browser blocked or cannot allocate a 2D canvas. Try a smaller image or disable privacy extensions that block canvas reads.",
  );
}
Defensive patterns

Strategy: type-guard

Validate before calling

function canGet2dContext(): boolean {
  try {
    return document.createElement("canvas").getContext("2d") !== null;
  } catch {
    return false;
  }
}

if (!canGet2dContext()) {
  throw new Error("Canvas 2D context unavailable in this environment.");
}

Type guard

const isCanvasContext = (ctx: CanvasRenderingContext2D | null): ctx is CanvasRenderingContext2D =>
  ctx !== null;

Try / catch

try {
  const ctx = canvas.getContext("2d");
  if (!ctx) throw new Error("Failed to get canvas context");
  // ... draw
} catch (error) {
  URL.revokeObjectURL(url);
  // surface a user-facing message; do not crash the tool workflow
  throw error;
}

Prevention

When it happens

Trigger: Uploading a very large image whose resized dimensions still exceed available canvas memory; running the app under a headless test runner or SSR render without a real 2D canvas polyfill; a browser privacy extension returning null from getContext to fingerprint-block canvas reads.

Common situations: Browser tab under heavy memory pressure from many large PDFs (this app targets 100GB+ workflows); automated tests (jsdom returns null for getContext unless canvas is configured); enterprise policy/extension disabling canvas image extraction.

Related errors


AI-assisted analysis of Stirling-Tools/Stirling-PDF@9ef20dcab8 (2026-08-13). Data as JSON: /api/errors/62c8185cda5fd5c7. Report an issue: GitHub.