KITFORMA · EDITORIAL ANSWER
Why does canvas export throw after drawing a cross-origin image?
KitForma editorial guide. Separate successful image display from permission to read canvas pixels, and set CORS mode before starting the image request.
Step-by-step answer
async function exportPng(url) {
const image = new Image();
image.crossOrigin = "anonymous";
image.src = url;
await image.decode();
const canvas = document.createElement("canvas");
canvas.width = image.naturalWidth;
canvas.height = image.naturalHeight;
canvas.getContext("2d").drawImage(image, 0, 0);
return new Promise((resolve, reject) => canvas.toBlob(
blob => blob ? resolve(blob) : reject(new Error("PNG export failed")),
"image/png"));
}
const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="2" height="1"><rect width="2" height="1" fill="red"/></svg>';
const url = URL.createObjectURL(new Blob([svg], { type: "image/svg+xml" }));
try {
const png = await exportPng(url);
console.log(png.type, png.size > 0);
} finally {
URL.revokeObjectURL(url);
}Sources and verification
Sources checked:
This editorial answer was prepared by KitForma with AI assistance. It is not presented as a real member question or an independent user review. Check the sources and the result with your own file; report corrections in the discussion.