为什么用JavaScript创建的svg元素不可见?

Bun*_*nyk 1 javascript svg dom

以下是我尝试创建圈子的方法:

var svgns = "http://www.w3.org/2000/svg/";
var circle = function(x, y) {
    this.x = x;
    this.y = y;
    this.element = document.createElementNS(
      svgns, "circle"
    );
    this.element.setAttributeNS(null, "cx", x);
    this.element.setAttributeNS(null, "cy", y);
    this.element.setAttributeNS(null, "r",  CIRCLE_RADIUS);
    this.element.setAttributeNS(null, "fill", randomColor());
    svg.appendChild(this.element);
}
circle(100, 100);
Run Code Online (Sandbox Code Playgroud)

仅显示最初在其中硬编码的圆圈.由我的脚本添加的另外两个是不可见的,但它们几乎是同一个,作为DevTools中的种子:

它们显然位于DOM中,如屏幕截图所示

这是CodePen的链接.也许我弄乱了一些名称空间或样式或什么?

Rob*_*son 5

你弄乱了命名空间.你要

var svgns = "http://www.w3.org/2000/svg";
Run Code Online (Sandbox Code Playgroud)

没有/最后与你的相比.

var CIRCLE_RADIUS = 10;
var svg = document.getElementById('canvas');

var randomColor = function() {
  return ['red', 'green', 'blue'][Math.floor(Math.random() * 3)];
}
var svgns = "http://www.w3.org/2000/svg";
var circle = function(x, y) {
    this.x = x;
    this.y = y;
    this.element = document.createElementNS(
      svgns, "circle"
    );
    this.element.setAttributeNS(null, "cx", x);
    this.element.setAttributeNS(null, "cy", y);
    this.element.setAttributeNS(null, "r",  CIRCLE_RADIUS);
    this.element.setAttributeNS(null, "fill", randomColor());
    svg.appendChild(this.element);
}
circle(100, 100);
circle(10, 10)
Run Code Online (Sandbox Code Playgroud)
<svg width="800" height="800" id="canvas">
    <circle cx="60" cy="10" r="10" fill="gray"/>
</svg>
Run Code Online (Sandbox Code Playgroud)