Skip to content

Instantly share code, notes, and snippets.

@snorfalorpagus
Created November 6, 2017 11:24
Show Gist options
  • Save snorfalorpagus/8c32cdff684c5096b36097a0bf425e79 to your computer and use it in GitHub Desktop.
Save snorfalorpagus/8c32cdff684c5096b36097a0bf425e79 to your computer and use it in GitHub Desktop.
var fs = require("fs");
var d3 = require("d3");
var jsdom = require("jsdom/lib/old-api");
var svg2png = require("svg2png")
var width = 400;
var height = 300;
jsdom.env({
html:'',
features:{ QuerySelector:true }, // you need query selector for d3 to work
done:function(errors, window){
window.d3 = d3.select(window.document); //get d3 into the dom
var container = window.d3.select("body").append("div").attr("class", "container");
var svg = container.append("svg")
.attr('xmlns', 'http://www.w3.org/2000/svg')
.attr("width", width)
.attr("height", height);
// set background color of SVG to white, otherwise it defaults to transparent
var bg = svg.append("rect")
.attr("width", "100%")
.attr("height", "100%")
.attr("fill", "#ffffff");
var circle = svg.append("circle")
.attr("cx", 30)
.attr("cy", 30)
.attr("r", 20)
.attr("stroke", "#cc0000")
.attr("stroke-width", 2)
;
var data = container.html();
fs.writeFileSync("output.svg", data)
svg2png(data)
.then(buffer => fs.writeFile("output.png", buffer))
.catch(e => console.error(e));
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment