gpt4 book ai didi

javascript - 从字符串创建 SVG DOM 元素

转载 作者:可可西里 更新时间:2023-11-01 01:27:59 28 4
gpt4 key购买 nike

我将如何从 String 创建 SVG DOM 元素?

例子:

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>';

最佳答案

您可以使用 DOMParser解析 XML 字符串。

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

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

为了跨浏览器正常工作,您需要设置 html 命名空间,即您的字符串需要如下所示...

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

关于javascript - 从字符串创建 SVG DOM 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24107288/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com