Skip to content

Instantly share code, notes, and snippets.

@julien-f
Last active June 2, 2017 06:51
Show Gist options
  • Select an option

  • Save julien-f/24ba7251f36a35ba2c28 to your computer and use it in GitHub Desktop.

Select an option

Save julien-f/24ba7251f36a35ba2c28 to your computer and use it in GitHub Desktop.
d3.js in Node.js
/**
* > npm install d3
*/
// In Node.js, d3.js works in a virtual document provided by jsdom.
var d3 = require('d3');
//--------
// Create the SVG element.
var svg = d3.select('body').append('svg')
// This attributes are required to form a valid SVG document .
.attr('xmlns', 'http://www.w3.org/2000/svg')
.attr('version', '1.1')
// Defines the viewPort (displayed area) of the document.
.attr('width', '800px')
.attr('height', '600px')
;
// Do whatever manipulation you want here.
// ...
// ...
// If you want to include inline CSS.
svg.append('defs').append('style')
.attr('type', 'text/css')
.text([
'<![CDATA[',
'path { stroke: black; }',
']]>'
].join('\n'))
;
// Extract the code from the code and preprend the doctype.
var svgContent = [
'<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"',
' "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">',
svg.remove().node().outerHTML
].join('');
// Prepend the XML header.
svgContent = [
'<?xml version="1.0" standalone="no"?>',
// If you want to add an external stylesheet.
'<?xml-stylesheet href="mystyle.css" type="text/css"?>',
svgContent
].join('');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment