1

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>

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. If you wait 2 seconds and press the button, the animation begins in the middle.

How can I correct animate SVG path's 'd' attribute via javascript?

adeptus
  • 35
  • 1
  • 5

1 Answers1

3

See 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();
}
artm
  • 8,554
  • 3
  • 26
  • 43