The SVG to PNG conversion engine behind vextm ICONS — a modern icon library for React applications.
Built for seamless integration into React and Next.js projects, this lightweight utility converts SVG elements or strings to high-quality PNG images using pure browser APIs.
- Zero dependencies — Pure browser Canvas API
- React-first — Designed for React and Next.js workflows
- TypeScript — Full type safety out of the box
- Tree-shakeable — Import only what you need
- Retina-ready — Built-in scale support for high-DPI exports
npm install vex-svg-to-pngimport { useRef } from 'react';
import { svgElementToPng } from 'vex-svg-to-png';
function IconExporter() {
const svgRef = useRef<SVGSVGElement>(null);
const handleExport = async () => {
if (!svgRef.current) return;
await svgElementToPng(svgRef.current, {
scale: 2,
backgroundColor: '#ffffff',
download: true,
fileName: 'icon',
});
};
return (
<div>
<svg ref={svgRef} viewBox="0 0 24 24" width="100" height="100">
<circle cx="12" cy="12" r="10" fill="#3498db" />
</svg>
<button onClick={handleExport}>Download PNG</button>
</div>
);
}Add 'use client' directive since the library requires browser APIs:
'use client';
import { useRef } from 'react';
import { svgElementToPng } from 'vex-svg-to-png';
export default function ExportPage() {
const svgRef = useRef<SVGSVGElement>(null);
const handleExport = async () => {
if (!svgRef.current) return;
await svgElementToPng(svgRef.current, { scale: 2, download: true });
};
return (
<div>
<svg ref={svgRef} viewBox="0 0 24 24" width="100" height="100">
<rect width="24" height="24" fill="#e74c3c" />
</svg>
<button onClick={handleExport}>Export</button>
</div>
);
}Convert an SVG DOM element to PNG.
Convert an SVG markup string to PNG.
| Option | Type | Default | Description |
|---|---|---|---|
width |
number |
SVG width | Output width in pixels |
height |
number |
SVG height | Output height in pixels |
backgroundColor |
string |
transparent | Background color (CSS string) |
scale |
number |
1 |
Scale factor (2 = retina) |
fileName |
string |
'image' |
Download filename |
download |
boolean |
false |
Trigger automatic download |
Both functions return Promise<SvgToPngResult>:
{
blob: Blob; // PNG as Blob
dataUrl: string; // PNG as base64 data URL
width: number; // Output width (scaled)
height: number; // Output height (scaled)
}import { svgStringToPng, SvgToPngError, SvgToPngErrorCode } from 'vex-svg-to-png';
try {
await svgStringToPng(svgMarkup);
} catch (error) {
if (error instanceof SvgToPngError) {
console.error(error.code, error.message);
}
}- Requires browser environment (Canvas API)
- External resources may be blocked by CORS
- Use
'use client'in Next.js App Router
MIT © vextmdev