JavaScript 库:SVG 转 PNG

以下是几个常用的 JavaScript 库,可用于将 SVG 转换为 PNG:

1. canvg

  • 特点:在客户端使用 Canvas 渲染 SVG 并导出为 PNG

  • GitHub: https://github.com/canvg/canvg

  • 使用方法

    import { Canvg } from 'canvg';
    
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    const v = await Canvg.from(ctx, svgString);
    await v.render();
    const png = canvas.toDataURL('image/png');

2. svg2png

  • 特点:Node.js 环境下使用,基于 PhantomJS

  • GitHub: https://github.com/domenic/svg2png

  • 使用方法

    const svg2png = require('svg2png');
    const fs = require('fs');
    
    fs.writeFileSync('dest.png', await svg2png(fs.readFileSync('source.svg')));

3. html-to-image

  • 特点:支持 SVG 和其他 HTML 元素转图片

  • GitHub: https://github.com/bubkoo/html-to-image

  • 使用方法

    import * as htmlToImage from 'html-to-image';
    
    const pngDataUrl = await htmlToImage.toPng(svgElement);

4. saveSvgAsPng

  • 特点:专门用于浏览器端 SVG 转 PNG

  • GitHub: https://github.com/exupero/saveSvgAsPng

  • 使用方法

    saveSvgAsPng(document.getElementById('svg'), 'diagram.png');

5. svg-to-img (Node.js)

  • 特点:现代 Node.js SVG 转图片工具

  • GitHub: https://github.com/wojtekmaj/svg-to-img

  • 使用方法

    const { svg2png } = require('svg-to-img');
    await svg2png(svgString).toFile('output.png');

选择建议:

  • 浏览器端:canvg 或 saveSvgAsPng

  • Node.js 环境:svg2png 或 svg-to-img

  • React/Vue 项目:html-to-image

大多数库都需要先将 SVG 加载到 DOM 或虚拟 DOM 中,然后通过 Canvas 进行渲染导出。