Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting SVG created with D3js to PNG

I have some charts created with D3js which I want to convert to a PNG-image through JavaScript so users can download the chart.

I have seen solutions that convert the SVG to a canvas and convert the canvas to an image. This will not work for me because the SVG uses classes to style the elements (which is something I'd rather not change because of mantainability), which causes the whole canvas to become black with very thick lines.

Is it possible to convert the SVG-charts to PNG directly?

The page is inside a Ruby on Rails project so it doesn't have to be a pure JavaScript solution, but I'd prefer to do this with JavaScript so I can also implement it in other projects.

like image 824
Leon Hooijer Avatar asked Oct 15 '13 09:10

Leon Hooijer


1 Answers

To display your svg within a canvas, you first have to convert it using a parser/renderer utility such as http://code.google.com/p/canvg/

(code adapted from: Convert SVG to image (JPEG, PNG, etc.) in the browser)

// the canvg call that takes the svg xml and converts it to a canvas
canvg('canvas', $("svg").html());

// the canvas calls to output a png
var canvas = document.getElementById("canvas");
var img = canvas.toDataURL("image/png");
like image 177
MZaragoza Avatar answered Sep 30 '22 09:09

MZaragoza