繁体   English   中英

如何将 SVG 元素从 String 添加到 DOM

[英]How to add SVG element from String to DOM

我想添加包含 rect 的 SVG,并将字符串中的标签使用到 DOM。

我不像我那样工作。

 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 属性...

 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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM