8

I need to create and manipulate some SVGs just with some server-side code (like with cron jobs) but I'm wondering if it's possible to use Snap.svg in this scenario where it's not included in a web page.

Will this work without Snap.svg being run in a browser?

Chad
  • 1,708
  • 1
  • 25
  • 44

1 Answers1

6

You can use jsdom to simulate browser environments and natively run Snap.svg in Node.js.

Example:

const jsdom = require('jsdom');
const xmlserializer = require('xmlserializer');

jsdom.env('', [require.resolve('snapsvg')], (error, window) => {
    if (error) throw error;

    const paper = window.Snap(100, 100);

    const rect = paper.rect(20, 20, 60, 60);
    rect.attr({fill: 'red'});

    const svg = xmlserializer.serializeToString(paper.node);
    window.close();

    console.log(svg);
});

Prints:

<svg height="100" version="1.1" width="100" xmlns="http://www.w3.org/2000/svg"><desc>Created with Snap</desc><defs/><rect x="20" y="20" width="60" height="60" style="" fill="#ff0000"/></svg>
hakatashi
  • 9,006
  • 2
  • 22
  • 22
  • jsdom does not implement getBBox... so it is a pretty unuseful – Perry Dec 01 '19 at 11:10
  • I'm interested in headless/cloud SnapSVG, maybe this JSDOM+Node-Canvas (SVG capable) implementation might be help, [Paper-jsdom-canvas](https://github.com/paperjs/paper-jsdom-canvas) – Big Rich Feb 07 '21 at 04:40