how to save/ export inline SVG styled with css from browser to image file

前端 未结 4 1693
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-01 17:43

I have a web app that is generating inline SVG graphics in the client on the fly based on user interaction. The graphic is defined partly by element attributes and partially by

4条回答
  •  渐次进展
    2021-02-01 18:02

    I think what is generally missing from these explanations on this topic, is the fact that a ".svg" file is actually just the markup in a text file.

    So get the svg contents from the dom, then save a text file with ".svg" filename.

    var text = $('#svg-container').html();
    text = text.slice(text.indexOf("")+4);
    var pom = document.createElement('a');
    pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
    pom.setAttribute('download', "image.svg");
    pom.style.display = 'none';
    document.body.appendChild(pom);
    pom.click();
    document.body.removeChild(pom);
    

    If for example illustrator is giving you an error like "SVG invalid, validate svg before continuing". Then double check the contents of the downloaded file, and make sure there isn't any unnecessary s or anything, and that text.slice(text.indexOf("")+4); didn't slice off anything important.

提交回复
热议问题