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?
js is a server-side JavaScript run-time environment. It's open-source, including Google's V8 engine, libuv for cross-platform compatibility, and a core library. Notably, Node. js does not expose a global "window" object, since it does not run within a browser.
Node (or more formally Node. js) is an open-source, cross-platform runtime environment that allows developers to create all kinds of server-side tools and applications in JavaScript. The runtime is intended for use outside of a browser context (i.e. running directly on a computer or server OS).
Node. js is a JavaScript framework for writing server-side applications. In its simplest form it allows you to trigger small JavaScript programs from the command line without any browser involved. For example, assuming node is installed if you write a JavaScript program in a file called hello.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With