javascript - 为什么从 JavaScript 创建的 svg 元素不可见?

标签 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 的链接.也许我弄乱了一些命名空间或样式之类的东西?

最佳答案

你弄乱了命名空间。你要

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>

关于javascript - 为什么从 JavaScript 创建的 svg 元素不可见?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42689208/

相关文章:

javascript - 无法将文本值分配给事件处理程序中 JQuery 元素的变量

html - 为什么多个 HTML 选择标签不显示在 DOM 中?

javascript - HTML 范围 slider 颜色根据输入从红色变为绿色

javascript - FabricJS 上的 Flash 图标

javascript - 如何从 Nodejs 中的 setTimeout 获取整数?

javascript - UnhandledPromiseRejectionWarning : Error: Script failed to execute- Electron execute script

javascript - Bootstrap -btn 组,数据切换 ="buttons": how to select a button with JS and deselect all others?

javascript - 模板中的 Angular.js 格式分钟

javascript - 单击页面加载后添加的 span 元素

javascript - 如何确定 Raphael text() 的准确高度?