Save svg to disk as png image - browser mismatch

I am trying to save a file as a png image, svg file generated with d3.js

. This code works fine in Chrome (saves the file to disk), but doesn't work in Firefox 32. Any ideas why?

$(".savePNG").click (function() {
    var svg = ($("#svgContainer")[0]).getElementsByTagName("svg")[0];
    var svg_xml = (new XMLSerializer).serializeToString(svg);   // extract the data as SVG text
    var data_uri = "data:image/svg+xml;base64," + window.btoa(svg_xml);

    var image = new Image;
    image.src = data_uri;
    image.onload = function()
    {
        var canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.height;

        var context = canvas.getContext("2d");
        context.clearRect(0, 0, image.width, image.height);
        context.drawImage(image, 0, 0);

        var a = document.createElement("a");
        a.download = "file.png";
        a.href = canvas.toDataURL("image/png");
        a.click ();
    };
});

      

If it provides any hint console.log (svg_xml.length + " " + data_uri.length);


on Chrome it returns 3501304 4668434 and on Firefox 3060753 4081030. So it seems that Firefox is missing some data, but I don't know what to do about it.

+3


source to share


1 answer


As suggested, the method .click()

doesn't work for firefox. But window.open(a.href, "_blank");

will work and open a new window with an image in it. You can right click to save it.



+1


source







All Articles