Reputation: 2721
Is there a way to just generate an svg and get it as a string without actually drawing it? I thought about render svg to a hidden div and then reading the inner html, but is there a cleaner way?
Upvotes: 2
Views: 2379
Reputation: 11810
One way to approach this problem is by checking how it would be done on the server side -- where there is no DOM.
As it turns out, the way to do this on the server side involves more or less the same "hack" used in the question. This is because d3 expects to work on a DOM; writing that DOM to HTML is really the only way to render it to a string.
Brief example:
var svg = window.d3.select('body')
.append('div').attr('class','container')
.append('svg'); // and lots of other stuff
//etc etc
svg.selectAll('.arc').doSomething('blah blah');
var svgAsString = d3.select('.container').html();
Upvotes: 0
Reputation: 1578
I would think you could do this:
var svg = d3.select("body").append("svg")
svg = d3.select(svg).remove()
Append the svg to the body, but immediately remove it. This will, of course, give you the 'd3 selection' object, not a string.
Upvotes: 2
Reputation: 27544
You can create a whole other DOM tree in javascript using createDocumentFragment()
. This is commonly used to create a complex section of the document and then add it all to the page in one step, so the browser only has to re-calculate layout once.
I haven't tested it, but you should also be able to use .innerHTML()
to extract everything you've created as a string that can be saved to file. Answers to this SO Question suggest that you can't call innerHTML()
directly on the document fragment itself, so you would have to add a body element to the fragment, add your SVG to it, and then get the inner HTML from the body node.
Upvotes: 0