Skip to content

Instantly share code, notes, and snippets.

@schabluk
Forked from benoitv-code/index.js
Created September 10, 2018 19:36
Show Gist options
  • Save schabluk/6803998807a86f72b329fa9ff5c3b11d to your computer and use it in GitHub Desktop.
Save schabluk/6803998807a86f72b329fa9ff5c3b11d to your computer and use it in GitHub Desktop.
d3, jsdom, node.js: server-side rendering
// Instructions:
// npm install --save d3 jsdom
const fs = require('fs');
const d3 = require('d3');
const jsdom = require('jsdom');
const { JSDOM } = jsdom;
const fakeDom = new JSDOM('<!DOCTYPE html><html><body></body></html>');
const outputLocation = './output.svg';
let body = d3.select(fakeDom.window.document).select('body');
// Make an SVG Container
let svgContainer = body.append('div').attr('class', 'container')
.append("svg")
.attr("width", 1280)
.attr("height", 1024);
// Draw a line
let circle = svgContainer.append("line")
.attr("x1", 5)
.attr("y1", 5)
.attr("x2", 500)
.attr("y2", 500)
.attr("stroke-width", 2)
.attr("stroke", "black");
// Output the result to console
console.log(body.select('.container').html());
// Output the result to file
fs.writeFileSync(outputLocation, body.select('.container').html());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment