Generating, viewing, and saving SVG client-side in browser

为君一笑 提交于 2019-12-02 21:20:30

I have solved my own problems, using modern HTML5 APIs.

The new show_svg() function looks like this:

function show_svg(evt) {
    var svg = document.getElementById("output-pic");
    var serializer = new XMLSerializer();
    var svg_blob = new Blob([serializer.serializeToString(svg)],
                            {'type': "image/svg+xml"});
    var url = URL.createObjectURL(svg_blob);

    var svg_win = window.open(url, "svg_win");
}

The browser's own Save functionality will work on this new window, and it doesn't involve any modifications to other files that "feel" weird or hacky. (It does seem a bit odd to serialise the SVG only to view it in the browser again, but this nonetheless seems to be The Right Thing under HTML5.)

The only unresolved problem is the disappearing markers—in fact, the problem gets worse, as now <use> elements don't work either! However, they're still there and functional in the code, so once the SVG is saved to a file, everything in the file works fine. And I've filed a bug with Mozilla, too.

...and to display the SVG in the same window, use:

window.location = url;

instead of

 window.open(url,...

Note also that the Titel tag is important, as this is used for the default file name when the svg file is saved.

I'm not sure if I understand your problem correctly but since I'm working on a similar problem I suggest the following(hope it works for you). With the code sample below you shouldn't have problems with the use tag

function show_svg(evt)
{
  var svg = document.getElementById("output-pic");
  var serializer = new XMLSerializer();
  var ser = serializer.serializeToString(svg);
  var w = window.open();
  w.document.open();
  w.document.write(ser);
  w.document.close();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!