Created
June 6, 2016 02:54
-
-
Save palanik/ba5e15dbbc7ea0574ae0d38252563b0d to your computer and use it in GitHub Desktop.
Using D3 on node.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* npm install d3 node-jsdom | |
*/ | |
var d3 = require('d3'); | |
var jsdom = require('node-jsdom'); | |
var http = require('http'); | |
function svgDOM(width, height) { | |
// Setup DOM | |
var document = jsdom.jsdom(); | |
var body = d3.select(document.body); | |
// Create svg node | |
return body.append('svg') | |
.attr('xmlns', 'http://www.w3.org/2000/svg') | |
.attr('xmlns:xlink', 'http://www.w3.org/1999/xlink') | |
.attr('width', width) | |
.attr('height', height); | |
} | |
function d3Draw() { | |
// Copied from https://gist.github.com/mbostock/45943c4af772e38b4f4e | |
var π = Math.PI, | |
τ = 2 * π, | |
n = 500; | |
var width = 960, | |
height = 960, | |
outerRadius = width / 2 - 20, | |
innerRadius = outerRadius - 80; | |
var svg = svgDOM(width, height); | |
svg | |
.append("g") | |
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")") | |
.selectAll("path") | |
.data(d3.range(0, τ, τ / n)) | |
.enter().append("path") | |
.attr("d", d3.svg.arc() | |
.outerRadius(outerRadius) | |
.innerRadius(innerRadius) | |
.startAngle(function(d) { return d; }) | |
.endAngle(function(d) { return d + τ / n * 1.1; })) | |
.style("fill", function(d) { return d3.hsl(d * 360 / τ, 1, .5); }); | |
//d3.select(self.frameElement).style("height", height + "px"); | |
return svg.node().outerHTML; | |
} | |
http.createServer( | |
function (req, res) { | |
// favicon - browser annoyance, ignore | |
if(req.url.indexOf('favicon.ico') >= 0) { | |
res.statusCode = 404 | |
return | |
} | |
res.writeHead(200, { "Content-Type": 'image/svg+xml' }); | |
res.end(d3Draw()); | |
} | |
) | |
.listen(8080, function() { | |
console.log("Server listening on port 8080"); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment