动态添加一个完整的svg形状(使用纯Javascript)

Dynamically add a full svg shape (with pure Javascript)

本文关键字:形状 svg Javascript 添加 一个 动态      更新时间:2023-09-26

我想用JS创建的SVG中的路径画一个正方形。但浏览器不接受这一点:

Javascript:

var svg = document.createElement('svg');
svg.width = "200";
svg.height = "200";
document.body.appendChild(svg);
var path = document.createElement('path');
path.setAttribute('d','M100,0 L200,100 100,200 0,100Z');
path.setAttribute('fill','red');
svg.appendChild(path);

HTML(输出):

<svg width="200" height="200">
  <path d="M100,0 L200,100 100,200 0,100Z" fill="red"/>
</svg>

createElement只能用于创建html元素。要创建SVG元素,必须使用createElementNS并提供SVG命名空间作为第一个参数。

还有document.body.appendChild('svg');可能是打字错误,因为您想要添加svg元素,而不是包含文本"svg"的字符串

var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('width','200');
svg.setAttribute('height','200');
document.body.appendChild(svg);
var path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
path.setAttribute('d','M100,0 L200,100 100,200 0,100Z');
path.setAttribute('fill','red');
svg.appendChild(path);

使用createElementNS而不是createElement