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

时间:2017-03-09 07:29:05

标签: javascript dom svg

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

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);

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

They are clearly in the DOM, as seen on screenshot

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

1 个答案:

答案 0 :(得分:5)

你弄乱了命名空间。你想要

var svgns = "http://www.w3.org/2000/svg";

与你的相比,最后没有。

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)
<svg width="800" height="800" id="canvas">
    <circle cx="60" cy="10" r="10" fill="gray"/>
</svg>