Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save j-medland/56ff5e181e2a21ef1f80683340cd39ef to your computer and use it in GitHub Desktop.
Save j-medland/56ff5e181e2a21ef1f80683340cd39ef to your computer and use it in GitHub Desktop.
Server Side SVG Rendering with D3.js 4.x and jsdom
const fs = require('fs')
const d3 = require('d3')
const jsdom = require('jsdom')
// define some data
let data = [20, 25, 30]
let dimensions = {x: 200, y: 200}
// invoke jsdom
jsdom.env(
{
html: '',
done: function (error, window) {
if (error) {
console.log(error)
}
// grab the jsdom body with d3
let body = d3.select(window.document.body)
// add an svg element
let svg = body.append('svg')
.attr('x', dimensions.x)
.attr('y', dimensions.y)
.attr('viewbox', '0 0 ' + dimensions.x + ' ' + dimensions.y)
// make sure the xmlns attribute is attached
.attr('xmlns', 'http://www.w3.org/2000/svg')
// do d3 stuff like a join
svg.selectAll('.circle')
.data(data)
.enter()
.append('circle')
.attr('class', 'circle')
.attr('cx', dimensions.x / 2)
.attr('cy', dimensions.y / 2)
.attr('r', function (d) { return d })
.style('fill-opacity', 0.3)
.style('fill', 'orange')
// finished - write out svg to file
fs.writeFileSync('output.svg', body.html())
}
})
Display the source blob
Display the rendered blob
Raw
<!--Output file with some manual pretty printing-->
<svg x="200" y="200" viewbox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
<circle class="circle" cx="100" cy="100" r="20" style="fill-opacity: 0.3; fill: orange;"></circle>
<circle class="circle" cx="100" cy="100" r="25" style="fill-opacity: 0.3; fill: orange;"></circle>
<circle class="circle" cx="100" cy="100" r="30" style="fill-opacity: 0.3; fill: orange;"></circle>
</svg>
{
"name": "server-side-d3",
"version": "0.0.1",
"description": "SVG rendering with D3 and jsdom",
"main": "index.js",
"scripts": {
"test": "node index"
},
"keywords": [
"d3",
"jsdom",
"svg"
],
"author": "https://github.com/j-medland",
"license": "MIT",
"dependencies": {
"d3": "^4.7.1",
"jsdom": "^9.11.0"
}
}

Server Side SVG Rendering with D3.js 4.x and jsdom

This gist is mostly based on Tom Pearson's Block but with a slightly clearer use of d3 with the window object provided by jsdom's 'done' function. This example works as expected but perhaps there are some subtleties that I have missed in Tom's approach.

Other examples of using D3 and jsdom can be found in the tests straight from the D3 github

To use this example, open a command-prompt/terminal and

cd /directory/containing/package.json
npm install
node test
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment