SVG Parser and Renderer for Canvas

4.0.3 · active · verified Sun Apr 19

canvg is a JavaScript library designed to parse SVG files and render them onto an HTML Canvas element. It handles various SVG features, animations, and interactions, making it suitable for displaying vector graphics in environments where direct SVG rendering might not be feasible or desired. The current stable version is 4.0.3, with recent releases addressing bug fixes and dependency updates. The project appears to have an active release cadence, with multiple minor and patch releases within major versions. A key differentiator is its versatility, supporting rendering in standard browser environments, Web Workers via OffscreenCanvas, and Node.js environments, requiring appropriate polyfills or peer dependencies for server-side rendering. It provides a programmatic API to load SVG content from URLs or strings and control its rendering lifecycle.

Common errors

Warnings

Install

Imports

Quickstart

This Node.js example demonstrates how to parse an SVG string and render it to a PNG file using `canvg` with the `node` preset.

import { promises as fs } from 'fs';
import { DOMParser } from '@xmldom/xmldom';
import { createCanvas } from 'canvas';
import fetch from 'node-fetch';
import { Canvg, presets } from 'canvg';

const preset = presets.node({
    DOMParser,
    canvas: { createCanvas },
    fetch
});

(async () => {
    const svgString = `
        <svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
            <rect x="10" y="10" width="180" height="180" fill="#ff0000" />
            <circle cx="100" cy="100" r="80" fill="#0000ff" />
            <text x="50" y="110" font-family="Arial" font-size="24" fill="white">Hello Canvg!</text>
        </svg>
    `;
    const outputFilePath = process.env.OUTPUT_PATH ?? 'output.png';

    const canvasInstance = preset.createCanvas(200, 200);
    const ctx = canvasInstance.getContext('2d');

    const v = Canvg.fromString(ctx, svgString, preset);

    // Render only first frame, ignoring animations.
    await v.render();

    const pngBuffer = canvasInstance.toBuffer();

    await fs.writeFile(outputFilePath, pngBuffer);
    console.log(`SVG rendered to ${outputFilePath}`);
})().catch(console.error);

view raw JSON →