如何通过javascript添加动画svg?

时间:2012-03-12 02:13:15

标签: javascript svg

<svg width="5cm" height="3cm"  viewBox="0 0 500 300">
<path id="path1" d="M100,250 C 100,50 400,50 400,250"
    fill="none" stroke="blue" stroke-width="7.06"  />
<circle r="17.64" fill="red">
<animateMotion dur="6s" repeatCount="1" rotate="auto" >
   <mpath xlink:href="#path1"/>
</animateMotion>
</circle>
</svg>

如果我在普通的html / svg文件中编写svg,它工作正常,圆圈动画正确。 但是,如果我通过javascript动态添加圆元素,则添加了圆圈,但它没有动画。怎么了? js代码:

    var svg = $("svg"); //use jquery
var circle = document.createElementNS("http://www.w3.org/2000/svg","circle");
circle.setAttribute("r", "5");
circle.setAttribute("fill", "red");
var ani = document.createElementNS("http://www.w3.org/2000/svg","animateMotion");
ani.setAttribute("dur", "26s");
ani.setAttribute("repeatCount", "indefinite");
ani.setAttribute("rotate", "auto");
var mpath = document.createElementNS("http://www.w3.org/2000/svg","mpath");
mpath.setAttribute("xlink:href", "#path1");
ani.appendChild(mpath);
circle.appendChild(ani);
svg.append(circle);

2 个答案:

答案 0 :(得分:6)

在“mpath”而不是setAttributeNS上使用setAttribute

mpath.setAttributeNS("http://www.w3.org/1999/xlink", "href", "#path1");

以下是演示:http://jsfiddle.net/zh553/

答案 1 :(得分:0)

同意在“mpath”而不是setAttributeNS上使用setAttribute

但至少对于Chrome(以及其他基于WebKit的浏览器?),似乎有必要注意http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-ElSetAttrNS,其中第二个参数是qualifiedName,即要创建或更改的属性的限定名称

mpath.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#path1");

或者,如果需要,更一般地说:

mpath.setAttributeNS("http://www.w3.org/1999/xlink",
                     mpath.lookupPrefix("http://www.w3.org/1999/xlink") + ":href",
                     "#path1");

还在https://bugs.webkit.org/show_bug.cgi?id=22958

进行了讨论
相关问题