我想通过按钮点击动画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>
如果按&#34;更改&#34;加载页面后立即按钮,将出现动画。但是如果你在页面加载后等待4秒(属性dur中指定的时间)并按下按钮,则没有动画。如果等待2秒钟并按下按钮,则动画从中间开始。
如何更正动画SVG路径&#39; d&#39;属性通过javascript?
答案 0 :(得分:1)
请参阅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();
}