I’d like to convert a simple dynamic svg snippet into a PNG data URI on the server. Something like this:
var svg = '<svg height="100" width="100"><circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" /></svg>'
console.log('<img src="data:image/png;base64,'+toPng(svg, 100, 100)+'">')
I’ve seen examples using imagemagick and some phantomJS variants, but I’m looking for an on-the-fly dynamic solution in node.js, preferably without I/O.
Here's a way to do it using Fabric.js:
Step 1: Install Cairo and node-canvas:
(I'm on Ubuntu 14.04, instructions for other OSes can be found here.)
Step 2: Install Fabric.js:
Step 3: Run the following JavaScript with
node
:Result:
(Ran on node v0.10.25.)
Special thanks to this question for the
fabric.loadSVGFromString
example.Take a look at svg-to-img.
It relies on headless Chrome under the hood to do the conversion.
To use svg-to-img in your project, run:
Here's how to convert a
svg
to a base64-encodedpng
:Disclaimer: I'm the author of svg-to-img.