使用javascript在SVG中添加路径

3
我正在尝试使用JavaScript将路径元素附加到一些内联SVG中,但我收到了错误消息:“未捕获的NotFoundError:尝试在不存在的上下文中引用节点”。有人能解释一下为什么这个JavaScript在我的HTML中不起作用吗?
<body>
    <svg height='500' width='500'></svg>


    <script>
        var svg =  document.getElementsByTagName("svg")[0];
        var pathElement = svg.appendChild("path");
    </script>

</body>
2个回答

5
appendChild方法需要传入一个元素而不是字符串,所以你需要像这样做...
var svg = document.getElementsByTagName("svg")[0];
var path = document.createElementNS("http://www.w3.org/2000/svg", "path");

// Use path.setAttribute("<attr>", "<value>"); to set any attributes you want

var pathElement = svg.appendChild(path);

0
任何路过的人想要看到它运行的工作示例:http://jsfiddle.net/huvd0fju/ HTML
<svg id="mysvg" width="100" height="100">
   <circle class="c" cx="50" cy="50" r="40" fill="#fc0" />
</svg> 

JS

var mysvg = document.getElementById("mysvg");
//uncomment for example of changing existing svg element attributes
/*
var mycircle = document.getElementsByClassName("c")[0];
mycircle.setAttributeNS(null,"fill","#96f");
*/
var svgns = "http://www.w3.org/2000/svg";
var shape = document.createElementNS(svgns, "rect");
shape.setAttributeNS(null,"width",50);
shape.setAttributeNS(null,"height",80);
shape.setAttributeNS(null,"fill","#f00");
mysvg.appendChild(shape);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接