Generate SVG files using NodeJS + D3

Saurabh
2 min readJul 23, 2019

--

Working on D3.js and SVG has always been one the most interesting task for me.

D3.js is undoubtedly the best library when it comes to work with visualization, but when it comes to SVG, It has its own quirks. One of which I faced in one of my recent task.

Task was related to draw user interactive process diagrams, for which frontend will get the parsed JSON data and using this data it draws the process diagram with the help of D3.js and SVG (Sound Simple, Isn’t It J)

Drawing one process diagram needed allot of shapes combined in one SVG, which obviously caused many DOM elements. Which was still okay since we had only one process diagram visible at one time.

Problem started when there was a requirement where we need to display a dashboard having thumbnails for each of the possible processes from which user can select which process diagram he need to look at.

At any cost, we could not afford to draw these diagrams for the thumbnails, since it will cause a lot many DOM element so we decided to generate SVG image file on the fly(On server), which we used as images in browser.

In addition, to generate these files I wanted to use the same code (d3 and SVG) which I wrote on frontend, and I achieved it using NodeJS.

Here is a code snippet that generate SVG file from the SVG dom element created with the help of d3.js

This will generate a svg file with the name “out.svg”.

Cheers!

--

--