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.
我需要使用一些服务器端代码(比如使用cron作业)来创建和操作一些SVG,但我想知道是否可以在这种情况下使用Snap.svg,它不包含在网页中。
Will this work without Snap.svg being run in a browser?
如果没有Snap.svg在浏览器中运行,这是否可行?
1 个解决方案
#1
5
You can use jsdom to simulate browser environments and natively run Snap.svg in Node.js.
您可以使用jsdom来模拟浏览器环境,并在Node.js中本机运行Snap.svg。
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>
#1
5
You can use jsdom to simulate browser environments and natively run Snap.svg in Node.js.
您可以使用jsdom来模拟浏览器环境,并在Node.js中本机运行Snap.svg。
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>