The html code below is a minimal example to create an svg element displaying a simple rough.js polygon generated from an array of data. I want to use the js code in a nodejs program that generates the same svg and saves it to a file. What would be the simplest way of achieving this?
<html>
<head>
<script src="https://unpkg.com/roughjs@latest/bundled/rough.js"></script>
</head>
<body>
<script>
var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
var rc = rough.svg(svg);
var data = [[40, 20], [140, 30], [100, 130]];
svg.appendChild(rc.polygon(data));
document.body.appendChild(svg);
</script>
</body>
</html>
(Answering my own question here)
The solution I found uses xmldom (from this github issue):
// file generate-rough-svg.js
const { DOMImplementation, XMLSerializer } = require('xmldom');
const xmlSerializer = new XMLSerializer();
const document = new DOMImplementation().createDocument('http://www.w3.org/1999/xhtml', 'html', null);
const rough = require('roughjs');
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
const rc = rough.svg(svg);
var data = [[40, 20], [140, 30], [100, 130]]
svg.appendChild(rc.polygon(data))
let xml = xmlSerializer.serializeToString(svg);
console.log(xml)
Now I can run
node generate-rough-svg.js > image.svg
to generate the svg file.
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