【问题标题】:How to create a valid svg element with javascript如何使用 javascript 创建有效的 svg 元素
【发布时间】:2019-08-07 23:06:45
【问题描述】:

我正在使用 SVG 并创建了一个 svg 元素。我使用 html 将 <rect> 元素直接添加到 svg 中,然后使用 javascript 创建了一个新元素(没有命名空间)<circle> 并将其附加到 svg 元素中。 <rect> 元素显示在 svg 视图框中,但 <circle> 元素未显示。

我在控制台上得到了<rect><circle> 并检查了构造函数。 <rect> 元素返回 SVGRectElement,但 <circle> 返回 HTMLUnknownElement。我创建了一个新的<circle> 元素(带有命名空间:https://www.w3.org/2000/svg)并检查了返回Element 的构造函数。

无论哪种方式,将命名空间和非命名空间 <circle> 元素都附加到 svg 不会出现在 svg 视图框中。那么如何使用 javascript 创建一个可识别的 svg 元素,该元素将返回 SVGCircleElement?

   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>

【问题讨论】:

  • 1.您需要像这样关闭&lt;rect&gt;id='svgrect' /&gt; 或像这样:id='svgrect'&gt;&lt;/rect&gt; 和 2. 始终使用 createElementNS
  • 抱歉我在这个问题中的代码错误。我在代码中正确关闭了所有标签
  • 在我的 javascript 代码中可见,我创建的第二个圆圈带有命名空间,它返回 function Element() { [native code] },它也没有显示在 SVG 中。

标签: javascript html svg constructor console


【解决方案1】:

从“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>

【讨论】:

  • 我已经为此做了 3 天不同的方法,现在才发现删除命名空间中的 's' 是解决方案。非常有意思。谢谢保罗
猜你喜欢
  • 2017-01-26
  • 2014-11-14
  • 2017-03-06
  • 2012-11-16
  • 2013-12-30
  • 2014-07-19
  • 2023-03-27
  • 2011-02-14
  • 2011-10-05
相关资源
最近更新 更多