Convert SVG to Raster Image Using HTML5 Canvas

Converting Scalable Vector Graphics (SVG) into raster formats such as PNG or JPEG can be executed entirely client-side using JavaScript and the HTML5 <canvas> element. This process involves serializing the SVG data, loading it into an HTML Image object via a Blob or Data URL, rendering that image onto a canvas context, and finally exporting the canvas contents as a raster image file.

Step 1: Prepare and Serialize the SVG

If the SVG is already present in the DOM, it must be serialized into an XML string. If the SVG is already an XML string, you can proceed directly to creating a Blob. Ensure the SVG element contains explicit width and height attributes or a well-defined viewBox to prevent scaling issues.

const svgElement = document.querySelector('svg');
const serializer = new XMLSerializer();
const svgString = serializer.serializeToString(svgElement);

Step 2: Create a Blob URL

Wrap the serialized SVG string in a Blob with the image/svg+xml MIME type and generate an Object URL. This allows the browser to treat the SVG data as an image source.

const svgBlob = new Blob([svgString], { type: 'image/svg+xml;charset=utf-8' });
const URL = window.URL || window.webkitURL || window;
const blobURL = URL.createObjectURL(svgBlob);

Step 3: Load the SVG into an Image Object

Instantiate an HTML Image object and assign the generated Blob URL to its src attribute. You must wait for the image’s onload event to fire before drawing it.

const image = new Image();
image.src = blobURL;

Step 4: Draw onto the Canvas and Export

Inside the onload callback, set up the canvas dimensions to match the SVG, render the image using CanvasRenderingContext2D.drawImage(), and export the result using toDataURL() or toBlob().

image.onload = () => {
    const canvas = document.createElement('canvas');
    canvas.width = image.width;
    canvas.height = image.height;

    const context = canvas.getContext('2d');
    context.drawImage(image, 0, 0);

    // Export as PNG Data URL
    const pngDataUrl = canvas.toDataURL('image/png');

    // Clean up memory
    URL.revokeObjectURL(blobURL);

    // Trigger download or use the raster data
    const downloadLink = document.createElement('a');
    downloadLink.download = 'exported-image.png';
    downloadLink.href = pngDataUrl;
    downloadLink.click();
};

Key Considerations