简体   繁体   中英

Save svg to disk as png image - browser discrepancy

I am trying to save to a file, as a png image, an svg plot that was created with d3.js . This code works fine on Chrome (saves the file to disk) but fails on 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 clue console.log (svg_xml.length + " " + data_uri.length);
on Chrome returns 3501304 4668434 and on Firefox 3060753 4081030. So it would seem that Firefox is missing some data but I don't know what to make of it.

As suggested the .click() method fails for firefox. But window.open(a.href, "_blank"); will work and open a new window with the image in it. You can right click to save it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM