如何通过javascript添加动画svg? [英] How to add an animated svg via javascript?
本文介绍了如何通过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动态添加circle元素,则添加了circle,但它没有动画。怎么了? js代码:
If I write the svg in plain html/svg file, it works fine, the circle animates correctly. But if I add the circle element dynamically via javascript, circle was added, but it didn't animate. What's wrong? js code:
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);
推荐答案
使用 setAttributeNS
onmpath而不是 setAttribute
。
Use setAttributeNS
on "mpath" instead of setAttribute
.
mpath.setAttributeNS("http://www.w3.org/1999/xlink", "href", "#path1");
这是一个演示: http://jsfiddle.net/zh553/
这篇关于如何通过javascript添加动画svg?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文