resvg-js

repository·main·Indexed 24 days ago

https://github.com/thx/resvg-js

A high-performance SVG renderer and toolkit powered by the Rust-based resvg engine. It enables fast and accurate SVG to PNG conversion across Node.js (via napi-rs), Deno, Bun, and Browsers (via WebAssembly). The library supports custom font loading, scaling options via fitTo, and provides both synchronous and asynchronous rendering methods.

Tokens
5.8K
Snippets
7
Records
45
Agent score
78%

What's inside resvg-js

  1. Use @resvg/resvg-wasm for WebAssembly-based SVG rendering

    main
    The @resvg/resvg-wasm package provides the WebAssembly (Wasm) binary version of resvg-js. It is designed for high-performance SVG rendering in environments that support WebAssembly, such as web browsers. It is powered by the Rust-based resvg engine.
  2. Install resvg-js via npm

    main

    The @resvg/resvg-js package uses optionalDependencies along with os and cpu fields to automatically select and install the correct platform-specific binary during installation.

    Supported Package Managers

    • npm v7+
    • cnpm 7.1.0+
    • pnpm

    Note: Using versions lower than those listed above may result in the incorrect platform package being downloaded.

    Important Installation Warning

    Do not use the --no-optional flag when installing, as this will prevent the necessary binary files from being installed:

    # AVOID THIS COMMAND
    npm install @resvg/resvg-js --no-optional
    npm install @resvg/resvg-js
  3. Use resvg-js in Deno

    main

    Starting with Deno 1.26.1, you can run native addons directly from Node.js imports. This provides performance close to native Node.js. You must use the --unstable, --allow-read, --allow-write, and --allow-ffi flags.

    deno run --unstable --allow-read --allow-write --allow-ffi example/index-deno.js
  4. Use resvg-js in the Browser via WebAssembly

    main

    To use resvg-js in a browser, you must first initialize the Wasm module using resvg.initWasm().

    1. Fetch the .wasm file (e.g., from https://unpkg.com/@resvg/resvg-wasm/index_bg.wasm).
    2. Initialize with await resvg.initWasm(wasmBuffer).
    3. Create a new resvg.Resvg instance.
    4. Call .render(svg, opts) to get the PNG data as a Uint8Array.

    For custom fonts in the browser, use the font.fontBuffers option with an array of ArrayBuffer objects.

    <script src="https://unpkg.com/@resvg/resvg-wasm"></script>
    <script>
      ;(async function () {
        // The Wasm must be initialized first
        await resvg.initWasm(fetch('https://unpkg.com/@resvg/resvg-wasm/index_bg.wasm'))
    
        const font = await fetch('./fonts/Pacifico-Regular.woff2')
        if (!font.ok) return
    
        const fontData = await font.arrayBuffer()
        const buffer = new Uint8Array(fontData)
    
        const opts = {
          fitTo: {
            mode: 'width', // If you need to change the size
            value: 800,
          },
          font: {
            fontBuffers: [buffer], // New in 2.5.0, loading custom fonts
          },
        }
    
        const svg = '<svg> ... </svg>' // Input SVG, String or Uint8Array
        const resvgJS = new resvg.Resvg(svg, opts)
        const pngData = resvgJS.render(svg, opts) // Output PNG data, Uint8Array
        const pngBuffer = pngData.asPng()
        const svgURL = URL.createObjectURL(new Blob([pngData], { type: 'image/png' }))
        document.getElementById('output').src = svgURL
      })()
    </script>
  5. Use resvg-js in Node.js

    main

    To render an SVG to PNG in Node.js, import Resvg from @resvg/resvg-js. You can pass an options object to configure background color, scaling (fitTo), and fonts.

    Key options:

    • background: A color string (e.g., 'rgba(238, 235, 230, .9)').
    • fitTo: An object with mode ('width' or 'height') and value to scale the output.
    • font: Configuration for fonts, including fontFiles (array of paths) and loadSystemFonts (boolean).

    After calling resvg.render(), use pngData.asPng() to get the buffer.

    const { promises } = require('fs')
    const { join } = require('path')
    const { Resvg } = require('@resvg/resvg-js')
    
    async function main() {
      const svg = await promises.readFile(join(__dirname, './text.svg'))
      const opts = {
        background: 'rgba(238, 235, 230, .9)',
        fitTo: {
          mode: 'width',
          value: 1200,
        },
        font: {
          fontFiles: ['./example/SourceHanSerifCN-Light-subset.ttf'], // Load custom fonts.
          loadSystemFonts: false, // It will be faster to disable loading system fonts.
        },
      }
      const resvg = new Resvg(svg, opts)
      const pngData = resvg.render()
      const pngBuffer = pngData.asPng()
    
      console.info('Original SVG Size:', `${resvg.width} x ${resvg.height}`)
      console.info('Output PNG Size  :', `${pngData.width} x ${pngData.height}`)
    
      await promises.writeFile(join(__dirname, './text-out.png'), pngBuffer)
    }
    
    main()