简体   繁体   English

Javascript SVG<g> 标签</g>

[英]Javascript SVG <g> tag

What I am trying to do: insert an svg into a inner most g tag我正在尝试做的事情:将 svg 插入最里面的 g 标签

What I have done so far:到目前为止我做了什么:

    let svg = document.querySelector('svg');
    let g = svg.getElementsByClassName('srd-default-link');

    let shape = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
    shape.id = 'circle';
    shape.setAttribute('cx', 25);
    shape.setAttribute('cy', 25);
    shape.setAttribute('r', 20);
    shape.setAttribute('style', 'fill: green');

     g[0].appendChild(shape);
}

The result: only able to insert it in the first layer g tag and not the inner most g tag结果:只能插入第一层g标签,不能插入最里面的g标签

In your source code there are two main problems:在您的源代码中有两个主要问题:

  1. You use the same id value many times.您多次使用相同的id值。 According to HTML documentation the id is used as unique identificator for an element.根据 HTML 文档, id用作元素的唯一标识符。
  2. You are "attaching" the circle to <svg> and not to <g> tag with the svg.appendChild(shape);您正在使用svg.appendChild(shape);将圆圈“附加”到<svg>而不是<g>标记;

You can do something similar to:你可以做类似的事情:

var svgElem = document.createElementNS("http://www.w3.org/2000/svg", "svg"); //create <svg>
var g = document.createElementNS("http://www.w3.org/2000/svg", "g"); //create <g>
g.classList.add("myClass");
svgElem.appendChild(g); //append <g> inside <svg>

var circle = document.createElementNS("http://www.w3.org/2000/svg", "circle"); //create <circle>
g.appendChild(circle); //append <circle> inside <g>

var g_2 = document.createElementNS("http://www.w3.org/2000/svg", "g"); //create another <g>
g_2.classList.add("myClass");
svgElem.appendChild(g_2); //append <g> inside <svg>


var coll = svgElem.getElementsByClassName("myClass"); //coll contains HTMLCollection

/* You cannot use coll.appendChild(circle);*/

coll[0].appendChild(circle); //append <circle> to the first <g> returned by getElementsByClassName("myClass");

I found out the reason why it did not work.我找到了它不起作用的原因。 I put a if condition,我放了一个if条件,

if (g.length !== 0) g[0].appendChild(shape);

and I put it in componentDidUpdate at the first line.我把它放在第一行的 componentDidUpdate 中。 Thanks @Wolfetto for helping in the initial part.感谢@Wolfetto 在最初部分的帮助。 I will leave it here for anyone who needs it in the future.我会把它留在这里给以后需要的人。

if (g.length !== 0) {
        for (let i = 0; i < g[0].childNodes.length; i++) {
            let item = g[0].childNodes[i];
            if (item.nodeName === 'g') item.appendChild(shape);
        }
    }

This is the code that append the shape into the inner most g tag of the svg element.这是将 append 形状放入 svg 元素的最内层 g 标记的代码。 I welcome any suggestion to improve code if any.我欢迎任何改进代码的建议(如果有的话)。

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

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