Last updated
SVG to PNG Conversion
Converting SVG to PNG rasterizes the vector graphic at a specific resolution. Unlike JPG, PNG supports transparency — if your SVG has transparent areas, they will be preserved in the PNG output. PNG uses lossless compression, making it ideal for graphics with sharp edges, text, and flat colors.
Canvas-Based Conversion
async function svgToPng(svgString, scale = 2) {
const parser = new DOMParser();
const doc = parser.parseFromString(svgString, 'image/svg+xml');
const svg = doc.documentElement;
// Get dimensions from viewBox or width/height attributes
const vb = svg.getAttribute('viewBox')?.split(/[\s,]+/).map(Number);
const w = vb ? vb[2] : parseInt(svg.getAttribute('width') || '300');
const h = vb ? vb[3] : parseInt(svg.getAttribute('height') || '300');
const blob = new Blob([svgString], { type: 'image/svg+xml' });
const url = URL.createObjectURL(blob);
const img = new Image();
img.src = url;
await new Promise(r => img.onload = r);
const canvas = document.createElement('canvas');
canvas.width = w * scale; // 2x for retina
canvas.height = h * scale;
const ctx = canvas.getContext('2d');
ctx.scale(scale, scale);
ctx.drawImage(img, 0, 0);
URL.revokeObjectURL(url);
return new Promise(r => canvas.toBlob(r, 'image/png'));
}
Retina / HiDPI Output
For crisp display on retina screens, render at 2× or 3× the display size.
A 400×300 SVG rendered at 2× produces an 800×600 PNG that displays sharply
on both standard and retina displays when used with CSS width: 400px.
This is the standard approach for app icons and UI graphics.