How do I save/export an SVG file after creating an SVG with D3.js (IE, safari and chrome)?

后端 未结 6 1025
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-28 19:50

I currently have a website using D3 and I\'d like the user to have the option to save the SVG as an SVG file. I\'m using crowbar.js to do this, but it only works on chrome.

6条回答
  •  臣服心动
    2020-11-28 20:05

    I tryed every solution here and nothing worked for me. My picture was always smaller than my d3.js canvas.

    I had to set the canvas width, height then do a clearRect on the context to make it works. Here is my working version

    Export function:

    var svgHtml = document.getElementById("d3-canvas"),
        svgData = new XMLSerializer().serializeToString(svgHtml),
        svgBlob = new Blob([svgData], {type:"image/svg+xml;charset=utf-8"}),
        bounding = svgHtml.getBoundingClientRect(),
        width = bounding.width * 2,
        height = bounding.height * 2,
        canvas = document.createElement("canvas"),
        context = canvas.getContext("2d"),
        exportFileName = 'd3-graph-image.png';
    
    //Set the canvas width and height before loading the new Image
    canvas.width = width;
    canvas.height = height;
    
    var image = new Image();
    image.onload = function() {
        //Clear the context
        context.clearRect(0, 0, width, height);
        context.drawImage(image, 0, 0, width, height);
    
        //Create blob and save if with FileSaver.js
        canvas.toBlob(function(blob) {
            saveAs(blob, exportFileName);
        });     
    };
    var svgUrl = URL.createObjectURL(svgBlob);
    image.src = svgUrl;
    

    It use FileSaver.js to save the file.

    This is my canvas creation, note that i solve the namespace issue here

    d3.js canvas creation:

    var canvas = d3.select("body")
        .insert("svg")
        .attr('id', 'd3-canvas')
        //Solve the namespace issue (xmlns and xlink)
        .attr("xmlns", "http://www.w3.org/2000/svg")
        .attr("xmlns:xlink", "http://www.w3.org/1999/xlink")
        .attr("width", width)
        .attr("height", height);
    

提交回复
热议问题