Search code examples
javascriptanimationsvgsequencesvg-animate

Restart SVG animation sequence from Javascript


I'm trying to restart SVG animation sequence from Javascript. Restart-button below will broke SVG animation sequence. How to restart/reset entire sequence?

document.getElementById("button").addEventListener("click", function() {
  document.getElementById("fore").beginElement();
});
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 150">
  <path id="track" fill="none" stroke="#000000" stroke-width="1" stroke-dasharray="10,10" d="M 50 100 L 950 50"/>
  <path id="plane" d="M-10 -10 L10 0L-10 10z" fill="red" />

  <animateMotion xlink:href="#plane" 
    id="fore" 
    begin="0s;back.end" 
    dur="2s" 
    fill="freeze" 
    repeatCount="1" 
    rotate="auto" 
    keyPoints="0;1" 
    keyTimes="0;1"
   ><mpath xlink:href="#track" /></animateMotion>
  
  <animateMotion xlink:href="#plane" 
    id="back" 
    begin="fore.end"  
    dur="2s" 
    fill="freeze" 
    repeatCount="1" 
    rotate="auto-reverse" 
    keyPoints="1;0" 
    keyTimes="0;1"
   ><mpath xlink:href="#track" /></animateMotion>
</svg>

<button id="button">RESTART</button>


Solution

  • You can use setCurrentTime on the entire svg element. I added an id of svgEl to the svg node and then when rest is clicked we do:

    document.getElementById('svgEl').setCurrentTime(0);
    

    Have a look at this:

    document.getElementById("button").addEventListener("click", function() {
      document.getElementById('svgEl').setCurrentTime(0);
    });
    <svg id="svgEl" version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 150">
      <path id="track" fill="none" stroke="#000000" stroke-width="1" stroke-dasharray="10,10" d="M 50 100 L 950 50"/>
      <path id="plane" d="M-10 -10 L10 0L-10 10z" fill="red" />
    
      <animateMotion xlink:href="#plane" 
        id="fore" 
        begin="0s;back.end" 
        dur="2s" 
        fill="freeze" 
        repeatCount="1" 
        rotate="auto" 
        keyPoints="0;1" 
        keyTimes="0;1"
        restart="always"
       ><mpath xlink:href="#track" /></animateMotion>
      
      <animateMotion xlink:href="#plane" 
        id="back" 
        begin="fore.end"  
        dur="2s" 
        fill="freeze" 
        repeatCount="1" 
        rotate="auto-reverse" 
        keyPoints="1;0" 
        keyTimes="0;1"
        restart="always"
       ><mpath xlink:href="#track" /></animateMotion>
    </svg>
    
    <button id="button">RESTART</button>