gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 08:27:43 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com