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

后端 未结 6 1027
佛祖请我去吃肉
佛祖请我去吃肉 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

    There are 5 steps. I often use this method to output inline svg.

    1. get inline svg element to output.
    2. get svg source by XMLSerializer.
    3. add name spaces of svg and xlink.
    4. construct url data scheme of svg by encodeURIComponent method.
    5. set this url to href attribute of some "a" element, and right click this link to download svg file.

    //get svg element.
    var svg = document.getElementById("svg");
    
    //get svg source.
    var serializer = new XMLSerializer();
    var source = serializer.serializeToString(svg);
    
    //add name spaces.
    if(!source.match(/^]+xmlns="http\:\/\/www\.w3\.org\/2000\/svg"/)){
        source = source.replace(/^]+"http\:\/\/www\.w3\.org\/1999\/xlink"/)){
        source = source.replace(/^

提交回复
热议问题