What is the best way to serialize SVG from the client DOM?

ぐ巨炮叔叔 提交于 2019-12-18 04:19:08

问题


I am working on interactive SVG/AJAX interfaces where elements are created and repositioned on-the-fly by users. I'd like to support the ability for users to export their current view to a PNG image and/or an SVG document. I'd really like the SVG document to be as simple as possible (without a lot of nested transforms). Is there any framework that already supports this?

I'm currently asking my users to use the Ctrl+Alt+PrntScrn technique, and I don't want to ask them to install any software/plugins.

The server-side code is implemented in PHP right now, if that helps. I've already implemented the ability to generate a PNG image from the "original" document (before the client makes any modifications) using ImageMagick.


回答1:


I'm assuming you need this to work only in browsers that support SVG.

Firefox, Safari, and Opera provide the non-standard XMLSerializer API, so you could do something like this:

var svg = document.getElementById('svg_root'); // or whatever you call it
var serializer = new XMLSerializer();
var str = serializer.serializeToString(svg);

From there, you can send it to the server and receive a PNG in return.

Here's Mozilla's developer page on serializing XML from the DOM.




回答2:


Opera has implementation of W3C's DOM→XML serializer. In XML mode innerHTML returns well-formed XML in Gecko.

HTML5 <canvas> can export its content as PNG file using toDataURL() and it's possible to paint any <img> element on canvas using drawImage(), so it should be possible to create <img src="data:application/svg+xml,…">, paint it on canvas and export as data: URL.



来源:https://stackoverflow.com/questions/227208/what-is-the-best-way-to-serialize-svg-from-the-client-dom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!