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
- External Assets: SVGs referencing external
resources (like remote fonts or external CSS stylesheets) may fail to
render on the canvas due to browser security models (tainted canvas).
Embed all fonts and styles directly inside
<style>tags within the SVG itself. - Canvas Tainting: When using
canvas.toDataURL()orcanvas.toBlob(), the canvas must not be tainted by cross-origin resources. - Background Color: Canvas defaults to a transparent
background. To export a non-transparent format like JPEG, fill the
canvas with a background color using
context.fillRect()before callingdrawImage().