Search code examples
svgjquery-animaterect

Is here a way to restart from the beginning the <animate> in a SVG element?


Just need to know how we can restart the sequence of the elements that are inside a <svg>. Thank you.

https://jsfiddle.net/nya13/4hzkno1f/3/

<html>

  <head>
  </head>

  <body>
    <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="margin: auto; background: rgb(255, 255, 255) none repeat scroll 0% 0%; display: block; shape-rendering: auto;" width="200px" height="200px" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid">
      <circle cx="50" cy="23" r="13" fill="#e15b64">
        <animate attributeName="cy" dur="1s" repeatCount="indefinite" calcMode="spline" keySplines="0.45 0 0.9 0.55;0 0.45 0.55 0.9" keyTimes="0;0.5;1" values="23;77;23"></animate>
      </circle>
    </svg>
    <button onclick="RestartAnimate();">Restart Animate</button>
  </body>
  <script>
    function RestartAnimate() {
        // Do something...
    }
  </script>
</html>

Solution

  • <button onclick="RestartAnimate();"> You must remove the semicolon

    Assign Animation Identifier <animate id="an"

    Assign begin="indefinite"

    In the example below, the cycle repeats three times after pressing the button Restart Animate

    <html>
    
      <head>
      </head>
    
      <body>
        <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="margin: auto; background: rgb(255, 255, 255) none repeat scroll 0% 0%; display: block; shape-rendering: auto;" width="200px" height="200px" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid">
          <circle cx="50" cy="23" r="13" fill="#e15b64">
            <animate id="an" attributeName="cy" dur="1s" repeatCount="3"  begin="indefinite" calcMode="spline" keySplines="0.45 0 0.9 0.55;0 0.45 0.55 0.9" keyTimes="0;0.5;1" values="23;77;23"></animate>
          </circle>
        </svg>
        <button onclick="RestartAnimate()">Restart Animate</button>
      </body>
      <script> 
       var animation = document.getElementById("an")
        function RestartAnimate() {
            animation.beginElement();
    }
      </script>
    </html>