PaddlePaddle/PaddleOCR · error
Failed to create a 2D canvas context.
Error message
Failed to create a 2D canvas context.
What it means
When converting an ImageData source to an ImageBitmap, sourceToImageBitmap() creates an offscreen canvas sized to the ImageData and requests a '2d' context. If getContext('2d') returns null — the browser refused to allocate a context (out of memory, too many contexts, canvas blocked by settings/extensions) — it throws this explicit error.
Source
Thrown at paddleocr-js/packages/core/src/platform/browser.ts:48
}
}
function hasDomConstructor(name: string): boolean {
return typeof (globalThis as Record<string, unknown>)[name] !== "undefined";
}
export async function sourceToImageBitmap(source: ImageSource): Promise<ImageBitmap> {
if (typeof ImageBitmap !== "undefined" && source instanceof ImageBitmap) return source;
if (source instanceof Blob) return createImageBitmap(source);
if (hasDomConstructor("HTMLCanvasElement") && source instanceof HTMLCanvasElement) {
return createImageBitmap(source);
}
if (source instanceof ImageData) {
const canvas = document.createElement("canvas");
canvas.width = source.width;
canvas.height = source.height;
const ctx = canvas.getContext("2d");
if (!ctx) throw new Error("Failed to create a 2D canvas context.");
ctx.putImageData(source, 0, 0);
return createImageBitmap(canvas);
}
if (hasDomConstructor("HTMLImageElement") && source instanceof HTMLImageElement) {
return createImageBitmap(source);
}
throw new Error("Unsupported image source. Use a Blob, ImageBitmap, ImageData, canvas, or img.");
}
async function sourceToClonedImageBitmap(source: ImageSource): Promise<ImageBitmap> {
if (typeof ImageBitmap !== "undefined" && source instanceof ImageBitmap) {
return createImageBitmap(source);
}
return sourceToImageBitmap(source);
}
export function bitmapToSourceMat(
cv: OpenCv,View on GitHub (pinned to 2661c7c0ef)
Solutions
- Convert to a Blob or ImageBitmap yourself before passing (createImageBlob accepts Blob/ImageBitmap without a canvas).
- Reuse/close canvases and free bitmaps (bitmap.close()) to avoid context exhaustion.
- In headless/CI Chrome, enable GPU/canvas (e.g. --enable-gpu, --disable-features that block canvas) or use a different source type.
Example fix
// before
const result = await ocr.predict(imageData); // ImageData path needs canvas
// after
const blob = new Blob([imageData.data.buffer], { type: 'image/png' });
// or render once and reuse an ImageBitmap:
const bmp = await createImageBitmap(imageData as unknown as ImageBitmapSource);
const result = await ocr.predict(bmp); Defensive patterns
Strategy: fallback
Validate before calling
// Pre-convert ImageData once; avoid the per-call canvas path entirely
function canCreateCanvas2d(): boolean {
try { return document.createElement('canvas').getContext('2d') !== null; } catch { return false; }
} Try / catch
try {
await ocr.predict(imageData);
} catch (e) {
if (e instanceof Error && e.message === 'Failed to create a 2D canvas context.') {
// fall back: encode once via an existing canvas/Blob, or re-run in a fresh tab/context
const blob = await encodeImageData(imageData);
return ocr.predict(blob);
}
throw e;
} Prevention
- Pass Blob or ImageBitmap sources instead of ImageData — they skip the canvas conversion path.
- Close() ImageBitmaps and release canvases in long-running sessions to avoid exhausting contexts.
- In headless CI browsers, verify canvas 2d works before running OCR tests.
When it happens
Trigger: Passing ImageData to predict() in a browser where 2D canvas contexts are exhausted or blocked: heavy tab with hundreds of canvases, privacy/hardening extensions disabling canvas, headless browsers with GPU/canvas disabled, or memory pressure on the GPU process.
Common situations: Batch-processing many frames reusing ImageData in long-running tabs; hardened browsers (canvas blocker extensions); CI headless Chrome without proper flags.
Related errors
- Failed to create 2D rendering context.
- PaddleOCR.js requires an HTTP(S) origin so model assets can
- Unsupported image source. Use a Blob, ImageBitmap, ImageData
- Failed to create a 2D canvas context in the OCR worker.
- ${modulePath}.model_dir must be null or an asset descriptor
AI-assisted analysis of PaddlePaddle/PaddleOCR@2661c7c0ef (2026-08-14).
Data as JSON: /api/errors/9d3c8de9dc4c1d2f.
Report an issue: GitHub.