简体   繁体   English

在没有jquery的情况下将g标签添加到svg标签中

[英]Add g tag into svg tag without jquery

I have svg element from this code我有来自这段代码的 svg 元素

let chartSVG = ReactDOM.findDOMNode(this.refChart).children[0];

I want to add a watermark contain g tag into that chartSVG.我想在该 chartSVG 中添加一个包含 g 标签的水印。

Should be basic DOM manipulation using createElementNS and appendChild() :应该是使用createElementNSappendChild()基本 DOM 操作:

 const xmlns = "http://www.w3.org/2000/svg"; const rect = document.createElementNS(xmlns, 'rect'); rect.setAttributeNS (null, "width", 50); rect.setAttributeNS (null, "height", 50); const g = document.createElementNS(xmlns, 'g'); g.appendChild(rect); const svg = document.getElementById('svg'); svg.appendChild(g);
 <svg id="svg"></svg>

Or, if you have your SVG content as a string, you can use a DOMParser() and import the fragment:或者,如果您将 SVG 内容作为字符串,则可以使用DOMParser()并导入片段:

 const g = new DOMParser().parseFromString( '<g xmlns="http://www.w3.org/2000/svg"><rect width="50" height="50"/></g>', 'application/xml'); const svg = document.getElementById('svg'); svg.appendChild(svg.ownerDocument.importNode(g.documentElement, true));
 <svg id="svg"></svg>

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

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