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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With