API Reference / @dasch-ng/web-utils / convertSvgToImage
Function: convertSvgToImage()
convertSvgToImage(
svgString,format):Promise<Blob|null>
Defined in: convert-svg-to-image.ts:22
Converts an SVG string to a raster image (PNG or JPEG) using HTML5 Canvas.
This function creates an image element from the SVG data URL, draws it onto a canvas, and then converts the canvas to a Blob in the specified format.
Parameters
svgString
string
The SVG markup as a string
format
The output image format, either 'png' or 'jpeg'. Defaults to 'png'
"png" | "jpeg"
Returns
Promise<Blob | null>
A Promise that resolves to a Blob containing the raster image data, or null if conversion fails
Throws
Error if unable to get 2D canvas context
Example
typescript
const svgString = '<svg width="100" height="100"><circle cx="50" cy="50" r="40" fill="red" /></svg>';
const blob = await convertSvgToImage(svgString, 'png');
if (blob) {
const url = URL.createObjectURL(blob);
// Use the URL for download or display
}