从字符串创建SVG DOM元素 [英] Creating an SVG DOM element from a String

查看:62
本文介绍了从字符串创建SVG DOM元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从 String 创建SVG DOM元素?

How would I go about creating an SVG DOM element from a String?

示例:

var svgStr = '<svg width="500" height="400" xmlns="http://www.w3.org/2000/svg"><!-- Created with Method Draw - http://github.com/duopixel/Method-Draw/ --><g><title>background</title><rect fill="#fff" id="canvas_background" height="402" width="502" y="-1" x="-1"/><g display="none" overflow="visible" y="0" x="0" height="100%" width="100%" id="canvasGrid"><rect fill="url(#gridpattern)" stroke-width="0" y="0" x="0" height="100%" width="100%"/></g></g><g><title>Layer 1</title><path id="svg_1" d="m118,242l64,-153l63,157c0,0 45,-71 49,-68c4,3 11,146 12,146c1,0 -173,-7 -173,-7c0,0 -61,-72 -61,-72c0,0 110,-156 46,-3z" fill-opacity="0.7" stroke-width="2" stroke="#995757" fill="#995757"/></g></svg>';

推荐答案

您可以使用

You can use DOMParser to parse an XML string.

var parser = new DOMParser();
var doc = parser.parseFromString(stringContainingXMLSource, "image/svg+xml");

已解析的字符串的根元素将为doc.documentElement

The root element for the parsed string will be doc.documentElement

要使此功能在跨浏览器中正常运行,您需要设置html命名空间,即您的字符串需要如下所示...

For this to work properly cross-browser you'll need to set the html namespace i.e. your string will need to look like this...

var svg2='<svg xmlns="http://www.w3.org/2000/svg" width="500" height="500" ...

这篇关于从字符串创建SVG DOM元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆