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
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
{
"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