Getting Started with SVG Export Using the Browser Canvas API
Converting SVG to raster images in the browser is simpler than most people think. Here's the core pattern.
The Canvas API handles SVG rendering natively—you parse the SVG string, load it as an image, then draw it to a canvas at any
resolution:
const svgBlob = new Blob([svgString], { type: 'image/svg+xml' });
const url = URL.createObjectURL(svgBlob);
const img = new Image();
img.onload = () => {
const canvas = document.createElement('canvas');
canvas.width = img.naturalWidth * scale;
canvas.height = img.naturalHeight * scale;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
canvas.toBlob(blob => {
const downloadUrl = URL.createObjectURL(blob);
});
};
img.src = url;
Why this works offline too
Once the page is loaded, all processing runs in the browser tab. No server round-trips. Turn off your WiFi and it still converts.
Two gotchas
- External fonts in SVGs won't render. If your SVG uses @import for fonts, embed them as base64 first.
- Canvas has a max size. Most browsers cap at 16,384×16,384px. Enough for 8K at 2x.
Top comments (0)