我在使用 SVG 时创建了一个 svg 元素。我添加了一个 <rect>
使用 html 将元素直接添加到 svg 中,然后我创建了一个新元素(没有命名空间)<circle>
使用 javascript 并将其附加到 svg 元素。 <rect>
元素显示在 svg View 框中,但 <circle>
元素没有显示。
我得到了 <rect>
和 <circle>
在控制台上检查构造函数。 <rect>
元素返回 SVGRectElement
但是 <circle>
返回 HTMLUnknownElement
.我创建了一个新的 <circle>
元素(命名空间:https://www.w3.org/2000/svg)并检查返回 Element
的构造函数.
无论哪种方式,附加命名空间和非命名空间<circle>
svg 的元素没有出现在 svg viewbox 中。那么我如何使用将返回 SVGCircleElement?
的 javascript 创建一个可识别的 svg 元素? .
var circle = document.createElement('circle');
circle.setAttribute('cx', '10');
circle.setAttribute('cy', '10');
circle.setAttribute('r', '30');
circle.setAttribute('fill', 'red');
var circle_2 = document.createElementNS('https://www.w3.org/2000/svg','circle');
circle.setAttribute('cx', '5');
circle.setAttribute('cy', '20');
circle.setAttribute('r', '30');
circle.setAttribute('fill', 'blue');
var svg = document.getElementById('svgx');
var rect = document.getElementById('svgrect');
svg.appendChild(circle);
svg.appendChild(circle_2);
console.log(svg.constructor); // SVGSVGElement() { [native code] }
console.log(rect.constructor); // HTMLRectElement() { [native code] }
console.log(circle.constructor); // HTMLUnknownElement() { [native code] }
console.log(circle_2.constructor); // Element() { [native code] }
<svg style='width: 100%;' id='svgx'>
<rect x='5' y='5' width='50' height='30' fill='black' id='svgrect'>
</svg>
最佳答案
从“https”中删除“s”。
var circle_2 = document.createElementNS('http://www.w3.org/2000/svg','circle');
尽管它看起来像一个 URL。它实际上只是一个字符串常量,指示此 XML 文件是一个 SVG 文件。命名空间常量必须与此处显示的完全相同。
您还需要将那部分代码的 circle
更改为 circle_2
。
var circle_2 = document.createElementNS('http://www.w3.org/2000/svg','circle');
circle_2.setAttribute('cx', '5');
circle_2.setAttribute('cy', '20');
circle_2.setAttribute('r', '30');
circle_2.setAttribute('fill', 'blue');
var svg = document.getElementById('svgx');
var rect = document.getElementById('svgrect');
svg.appendChild(circle_2);
<svg style='width: 100%;' id='svgx'>
<rect x='5' y='5' width='50' height='30' fill='black' id='svgrect'>
</svg>
关于javascript - 如何使用 javascript 创建有效的 svg 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55206823/