2015-05-28 144 views
0

我想通过按钮点击动画svg路径,但它不起作用。通过javascript动画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/

如果按页面加载后右侧的“更改”按钮,动画会出现。但是,如果您在页面加载后等待4秒(在属性dur中指定的时间)并按下按钮,则不会显示动画。如果等待2秒钟并按下按钮,则动画从中间开始。

我该如何通过JavaScript更正动画SVG路径的“d”属性?

+0

尝试添加动画作为' artm

回答

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(); 
} 
+0

它工作!谢谢! – adeptus