[英]Animate SVG path via javascript
I want to animate svg path by button click, but it's not working. 我想通过按钮单击为svg路径设置动画,但是它不起作用。
<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>
http://jsfiddle.net/c5mzn6d0/ http://jsfiddle.net/c5mzn6d0/
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. 但是,如果您在页面加载后等待4秒钟(在属性dur中指定的时间)并按下按钮,则没有动画。 If you wait 2 seconds and press the button, the animation begins in the middle. 如果您等待2秒钟并按下按钮,动画将从中间开始。
How can I correct animate SVG path's 'd' attribute via javascript? 如何通过JavaScript校正SVG路径的“ d”属性动画?
See http://jsfiddle.net/c5mzn6d0/4/ 参见http://jsfiddle.net/c5mzn6d0/4/
Add 加
animate.beginElement();
after you append the animation: 追加动画后:
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.