通过javascript设置SVG路径的动画 [英] Animate SVG path via javascript
本文介绍了通过javascript设置SVG路径的动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想通过单击按钮为svg路径设置动画,但是它不起作用.
I want to animate svg path by button click, but it's not working.
<svg width="100" height="50">
<path id="path1" d="M 10 10 L 40 20 20 40" fill="none" stroke="blue" stroke-width="2" />
</svg>
<button type="button" id="btn">Change</button>
<script>
var btn = document.getElementById('btn');
btn.onclick = function () {
var path = document.getElementById('path1');
var animate = document.createElementNS("http://www.w3.org/2000/svg","animate");
animate.setAttribute('attributeName', 'd');
animate.setAttribute('dur', 's');
animate.setAttribute('fill', 'freeze');
animate.setAttribute('values', 'M 10 10 L 40 20 20 40; M 30 10 L 10 40 40 30');
path.appendChild(animate);
}
</script>
如果在页面加载后立即按更改"按钮,则会出现动画.但是,如果您在页面加载后等待4秒钟(在属性dur中指定的时间),然后按下按钮,则没有动画.如果您等待2秒钟并按下按钮,动画将从中间开始.
If you press the "Change" button right after the page is loaded, the animation will appear. But if you wait 4 seconds after the page loads (the time specified in the attribute dur) and press the button, no animation. If you wait 2 seconds and press the button, the animation begins in the middle.
如何通过javascript校正SVG路径的'd'属性动画?
How can I correct animate SVG path's 'd' attribute via javascript?
推荐答案
请参见 http://jsfiddle.net/c5mzn6d0/4/
添加
animate.beginElement();
在添加动画之后:
var btn = document.getElementById('btn');
btn.onclick = function () {
var path = document.getElementById('path1');
var animate = document.createElementNS("http://www.w3.org/2000/svg","animate");
animate.setAttribute('attributeName', 'd');
animate.setAttribute('dur', '1s');
animate.setAttribute('fill', 'freeze');
animate.setAttribute('values', 'M 10 10 L 40 20 20 40; M 30 10 L 10 40 40 30');
path.appendChild(animate);
animate.beginElement();
}
这篇关于通过javascript设置SVG路径的动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文