resvg-js

A high-performance SVG renderer and toolkit, powered by Rust based resvg an...

README

resvg-js


resvg-js is a high-performance SVG renderer and toolkit, powered by Rust based resvg, with Node.js backend using napi-rs, also a pure WebAssembly backend.


Please use all lowercase resvg-js when referencing project names.

💖 🙏 Sponsoring me

Your sponsorship means a lot to me. It will help me sustain my projects actively and make more of my ideas come true. Much appreciated!


Features


- Fast, safe and zero dependencies, with correct output.
- Convert SVG to PNG, includes cropping, scaling and setting the background color.
- Support system fonts and custom fonts in SVG text.
- v2: Gets the width and height of the SVG and the generated PNG.
- `v2`: Support for outputting simplified SVG strings, such as converting shapes(rect, circle, etc) to ``.
- v2: Support WebAssembly.
- v2: Support to get SVG bounding box and crop according to bounding box.
- `v2`: Support for loading images of external links in ``.
- No need for node-gyp and postinstall, the .node file has been compiled for you.
- Cross-platform support, including Apple M Chips.
- Support for running as native addons in Deno.

Sponsor


Alipay(支付宝)


Installation


Node.js


  1. ```shell
  2. npm i @resvg/resvg-js
  3. ```

Browser(Wasm)


  1. ```html
  2. <script src="https://unpkg.com/@resvg/resvg-wasm"></script>
  3. ```

Example


Node.js Example


This example will load Source Han Serif, and then render the SVG to PNG.

  1. ```shell
  2. node example/index.js

  3. Loaded 1 font faces in 0ms.
  4. Font './example/SourceHanSerifCN-Light-subset.ttf':0 found in 0.006ms.
  5. Done in 55.65491008758545 ms
  6. ```

Deno Example


  1. ```shell
  2. deno run --unstable --allow-read --allow-write --allow-ffi example/index-deno.js

  3. [2022-11-16T15:03:29Z DEBUG resvg_js::fonts] Loaded 1 font faces in 0.067ms.
  4. [2022-11-16T15:03:29Z DEBUG resvg_js::fonts] Font './example/SourceHanSerifCN-Light-subset.ttf':0 found in 0.001ms.
  5. Original SVG Size: 1324 x 687
  6. Output PNG Size  : 1200 x 623
  7. Done in 66 ms
  8. ```

Usage


Node.js


  1. ```js
  2. const { promises } = require('fs')
  3. const { join } = require('path')
  4. const { Resvg } = require('@resvg/resvg-js')

  5. async function main() {
  6.   const svg = await promises.readFile(join(__dirname, './text.svg'))
  7.   const opts = {
  8.     background: 'rgba(238, 235, 230, .9)',
  9.     fitTo: {
  10.       mode: 'width',
  11.       value: 1200,
  12.     },
  13.     font: {
  14.       fontFiles: ['./example/SourceHanSerifCN-Light-subset.ttf'], // Load custom fonts.
  15.       loadSystemFonts: false, // It will be faster to disable loading system fonts.
  16.       // defaultFontFamily: 'Source Han Serif CN Light', // You can omit this.
  17.     },
  18.   }
  19.   const resvg = new Resvg(svg, opts)
  20.   const pngData = resvg.render()
  21.   const pngBuffer = pngData.asPng()

  22.   console.info('Original SVG Size:', `${resvg.width} x ${resvg.height}`)
  23.   console.info('Output PNG Size  :', `${pngData.width} x ${pngData.height}`)

  24.   await promises.writeFile(join(__dirname, './text-out.png'), pngBuffer)
  25. }

  26. main()
  27. ```

Bun


Starting with Bun 0.8.1, resvg-js can be run directly in Bun without any modification to the JS files, and is fully compatible with the syntax in Node.js.

  1. ```shell
  2. bun example/index.js
  3. ```

Deno


Starting with Deno 1.26.1, there is support for running Native Addons directly from Node.js.
This allows for performance that is close to that found in Node.js.

  1. ```shell
  2. deno run --unstable --allow-read --allow-write --allow-ffi example/index-deno.js
  3. ```

  1. ```js
  2. import * as path from 'https://deno.land/std@0.159.0/path/mod.ts'
  3. import { Resvg } from 'npm:@resvg/resvg-js'
  4. const __dirname = path.dirname(path.fromFileUrl(import.meta.url))

  5. const svg = await Deno.readFile(path.join(__dirname, './text.svg'))
  6. const opts = {
  7.   fitTo: {
  8.     mode: 'width',
  9.     value: 1200,
  10.   },
  11. }

  12. const t = performance.now()
  13. const resvg = new Resvg(svg, opts)
  14. const pngData = resvg.render()
  15. const pngBuffer = pngData.asPng()
  16. console.info('Original SVG Size:', `${resvg.width} x ${resvg.height}`)
  17. console.info('Output PNG Size  :', `${pngData.width} x ${pngData.height}`)
  18. console.info('✨ Done in', performance.now() - t, 'ms')

  19. await Deno.writeFile(path.join(__dirname, './text-out-deno.png'), pngBuffer)
  20. ```

WebAssembly


This package also ships a pure WebAssembly artifact built with wasm-bindgen to run in browsers.

Browser


  1. ```html
  2. <script src="https://unpkg.com/@resvg/resvg-wasm"></script>
  3. <script>
  4.   ;(async function () {
  5.     // The Wasm must be initialized first
  6.     await resvg.initWasm(fetch('https://unpkg.com/@resvg/resvg-wasm/index_bg.wasm'))
  7.     const font = await fetch('./fonts/Pacifico-Regular.woff2')
  8.     if (!font.ok) return
  9.     const fontData = await font.arrayBuffer()
  10.     const buffer = new Uint8Array(fontData)
  11.     const opts = {
  12.       fitTo: {
  13.         mode: 'width', // If you need to change the size
  14.         value: 800,
  15.       },
  16.       font: {
  17.         fontBuffers: [buffer], // New in 2.5.0, loading custom fonts
  18.       },
  19.     }
  20.     const svg = '<svg> ... </svg>' // Input SVG, String or Uint8Array
  21.     const resvgJS = new resvg.Resvg(svg, opts)
  22.     const pngData = resvgJS.render(svg, opts) // Output PNG data, Uint8Array
  23.     const pngBuffer = pngData.asPng()
  24.     const svgURL = URL.createObjectURL(new Blob([pngData], { type: 'image/png' }))
  25.     document.getElementById('output').src = svgURL
  26.   })()
  27. </script>
  28. ```