Stirling-Tools/Stirling-PDF · error · Error

Failed to get canvas context

Error message

Failed to get canvas context

What it means

Thrown in processImageTransparency (removeWhiteBackground) after canvas.getContext("2d") returned null. The function immediately calls ctx.drawImage and ctx.getImageData to read pixel data for white-background removal, so a null context is fatal. Same root class as the imageToPdfUtils case but on the transparency path where it must read pixel data.

Source

Thrown at frontend/editor/src/core/utils/imageTransparency.ts:54

        img.src = e.target?.result as string;
      };
      reader.onerror = () => {
        reject(new Error("Failed to read image file"));
      };
      reader.readAsDataURL(imageFile);
    }
  });
}

function processImageTransparency(
  img: HTMLImageElement,
  options: TransparencyOptions,
): string {
  const canvas = document.createElement("canvas");
  const ctx = canvas.getContext("2d");

  if (!ctx) {
    throw new Error("Failed to get canvas context");
  }

  canvas.width = img.width;
  canvas.height = img.height;

  ctx.drawImage(img, 0, 0);

  const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
  const data = imageData.data;

  let lowerBound = options.lowerBound || DEFAULT_LOWER_BOUND;
  let upperBound = options.upperBound || DEFAULT_UPPER_BOUND;

  if (options.autoDetectCorner) {
    const cornerColor = detectCornerColor(imageData);
    const tolerance = options.tolerance || 10;
    lowerBound = {
      r: Math.max(0, cornerColor.r - tolerance),

View on GitHub (pinned to 9ef20dcab8)

Solutions

  1. Guard the feature behind a capability check: attempt a tiny canvas getContext('2d') at module init and disable the transparency tool if unavailable.
  2. Test in the target browser, not jsdom, since getImageData requires a real rendering backend.
  3. Reduce concurrent image work to keep canvas backing-store allocation succeeding.
  4. Catch the error at the UI layer and show a clear message rather than failing silently.

Example fix

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

// after
const ctx = canvas.getContext("2d", { willReadFrequently: true });
if (!ctx) {
  throw new Error(
    "Unable to start background removal: 2D canvas context unavailable in this browser/session.",
  );
}
Defensive patterns

Strategy: type-guard

Validate before calling

function supportsImageDataRead(): boolean {
  try {
    const c = document.createElement("canvas");
    c.width = 1; c.height = 1;
    const ctx = c.getContext("2d", { willReadFrequently: true });
    return !!ctx && typeof ctx.getImageData === "function";
  } catch {
    return false;
  }
}

Type guard

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

Try / catch

try {
  const result = await removeWhiteBackground(file, opts);
} catch (error) {
  if (error instanceof Error && error.message === "Failed to get canvas context") {
    // show "background removal unsupported in this browser" UI
  }
  throw error;
}

Prevention

When it happens

Trigger: Invoking removeWhiteBackground on a system that cannot produce a 2D canvas context; privacy extensions blocking getImageData (some return a tainted/empty context instead of null); running the transparency feature in a non-browser test harness.

Common situations: Headless test runners without canvas polyfills; the same 100GB+ memory-pressure tab; canvas-read-blocking browser policies that cause getContext to return null.

Related errors


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