使用JavaScript创建SVG标记

Ric*_*ard 52 javascript svg

如何使用JavaScript创建SVG元素?我试过这个:

var svg = document.createElement('SVG');
    svg.setAttribute('style', 'border: 1px solid black');
    svg.setAttribute('width', '600');
    svg.setAttribute('height', '250');
    svg.setAttribute('version', '1.1');
    svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
document.body.appendChild(svg);
Run Code Online (Sandbox Code Playgroud)

然而,它创建了一个零宽度和零高度的SVG元素.

TeC*_*n4K 77

试试这个 :

var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute('style', 'border: 1px solid black');
svg.setAttribute('width', '600');
svg.setAttribute('height', '250');
svg.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink");
document.body.appendChild(svg);
Run Code Online (Sandbox Code Playgroud)

  • 太棒了 - 谢谢!是我,还是SVG真是挑剔? (6认同)
  • 谢谢@ErikDahlström,纠正.那么svg.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns:xlink","http://www.w3.org/1999/xlink")呢??命名空间真的有必要吗? (4认同)
  • 如果你要使用`xlink:href`标签,那绝对是必要的.否则,不是那么多. (3认同)
  • “ svg:svg”?普通的旧“ svg”也可以正常工作。同样,所有浏览器都忽略“版本”,因此添加它有点浪费。 (2认同)

Ron*_*ton 8

.createElementNSsvgpath元素的必需方法。下面的例子。

var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
var path1 = document.createElementNS("http://www.w3.org/2000/svg", 'path');
var path2 = document.createElementNS("http://www.w3.org/2000/svg", 'path');

svg.setAttribute("aria-hidden","true");
svg.setAttribute('viewbox', '0 0 24 24');
svg.setAttribute('width', '24px');
svg.setAttribute('height', '24px');

path1.setAttribute('d', 'M0 0h24v24H0z');
path1.setAttribute('fill', 'none');

path2.setAttribute('d', 'M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 17.93c-3.95-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2v1.93zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H8v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41c2.93 1.19 5 4.06 5 7.41 0 2.08-.8 3.97-2.1 5.39z');
path2.setAttribute('fill', '#2962ff');

svg.appendChild(path1);
svg.appendChild(path2);
document.body.appendChild(svg);
Run Code Online (Sandbox Code Playgroud)

  • 对于那些在开发工具中查看 DOM 的人来说,不要被愚弄 - 如果您使用 `innerHTML` 或 `outerHTML` 直接分配 svg 标记,您将看到 `xmlns=http://www.w3.org/2000/ svg` 在树中的标签表示中。如果您使用“createElementNS”,您将看不到它*但它仍然在那里*!您必须使用“createElementNS”,否则 ns 将不存在。对我来说,关键的问题是,当使用 JS 并添加“path”时,您不需要使用“innerHTML”显式 ns 声明,它会继承。如果您使用“createElement”,它不会继承,因此您还必须使用“createElementNS”。 (6认同)