如何将SVG元素从字符串添加到DOM [英] How to add SVG element from String to DOM
本文介绍了如何将SVG元素从字符串添加到DOM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想添加包括rect的SVG,并使用字符串中的标签到DOM.
I would like to add SVG which includes rect and use tags from a string to the DOM.
我不会像以前那样接缝工作.
I doesn't seams to work the way I do.
var documentAsString =
'<?xml version="1.0" encoding="UTF-8"?>\
<document xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">\
<svg id="container" >\
<g xmlns:xlink="http://www.w3.org/1999/xlink">\
<rect x="50" y="50" width="50" height="50" fill="red"/>\
<use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#shape" x="200" y="50" fill="blue"></use>\
</g>\
</svg>\
</document>\
';
var newDocument = (new DOMParser()).parseFromString(documentAsString, "text/xml");
var container = newDocument.getElementById("container");
var useContainer = document.getElementById('use-container');
useContainer.removeChild(useContainer.firstElementChild);
useContainer.appendChild(container.getElementsByTagName('g')[0]);
<svg>
<defs>
<g id="shape">
<rect x="50" y="50" width="50" height="50" />
<circle cx="50" cy="50" r="50" />
</g>
</defs>
<use xlink:href="#shape" x="50" y="50" />
<g id="use-container" xmlns:xlink="http://www.w3.org/1999/xlink">
<rect x="10" y="10" width="50" height="50" fill="red"></rect>
</g>
</svg>
推荐答案
SVG元素必须位于svg命名空间中,即具有一个具有适当值的xmlns属性...
The SVG element needs to be in the svg namespace i.e. have an xmlns attribute with the appropriate value...
var documentAsString =
'<?xml version="1.0" encoding="UTF-8"?>\
<document xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">\
<svg xmlns="http://www.w3.org/2000/svg" id="container" >\
<g xmlns:xlink="http://www.w3.org/1999/xlink">\
<rect x="50" y="50" width="50" height="50" fill="red"/>\
<use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#shape" x="200" y="50" fill="blue"></use>\
</g>\
</svg>\
</document>\
';
var newDocument = (new DOMParser()).parseFromString(documentAsString, "text/xml");
var container = newDocument.getElementById("container");
var useContainer = document.getElementById('use-container');
useContainer.removeChild(useContainer.firstElementChild);
useContainer.appendChild(container.getElementsByTagName('g')[0]);
<svg>
<defs>
<g id="shape">
<rect x="50" y="50" width="50" height="50" />
<circle cx="50" cy="50" r="50" />
</g>
</defs>
<use xlink:href="#shape" x="50" y="50" />
<g id="use-container" xmlns:xlink="http://www.w3.org/1999/xlink">
<rect x="10" y="10" width="50" height="50" fill="red"></rect>
</g>
</svg>
这篇关于如何将SVG元素从字符串添加到DOM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文