【问题标题】:Append a path to SVG with javascript使用 javascript 将路径附加到 SVG
【发布时间】:2013-09-12 17:35:46
【问题描述】:
我正在尝试使用 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>
【问题讨论】:
标签:
javascript
svg
appendchild
【解决方案1】:
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);
【解决方案2】:
任何路过的人想要看到它的工作示例:
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);