How to reset the timer of SVG animation when using

2019-07-23 03:33发布

问题:

I use elt.beginElementAt(-5) on SVG animation with dur="10s", it's worked in 5s, normal. BUT if at the end of an animation (i.e. at 5 seconds after launch elt.beginElementAt(-5) cmd) I want to trigger it again, It doesn't work!

I have to wait for the "truth" duration (10s in this example), to be able to restart the animation. Nothing happens if I try between 5s and 10s after my first elt.beginElementAt(-5) command...

So, how to reset the timer? How to ignore the "normal" duration?

Thanks.

回答1:

To have SVG start and reset functions work together, set the fill attribute.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
  <meta charset="utf-8" />
  <title>Scalable Vector Graphics (SVG) - SVG Animations</title>

  <!-- Scaffold -->
  <style>
    /* <![CDATA[ */
    body {
      margin-left: 100px;
    }

    svg {
      border: 1px solid black;
      width: 600px;
      height: 400px;
    }

    svg * {
      fill: none;
      stroke: #000000;
      stroke-width: 1px;
    }
    /* ]]> */
  </style>


  <script>
    /* <![CDATA[ */
    function go() {
      var elements = document.getElementsByTagName("animate");
      for (var i = 0; i < elements.length; i++) {
        elements[i].setAttribute("fill", "freeze");
        elements[i].beginElement();
      }
    }

    function reset() {
      var elements = document.getElementsByTagName("animate");
      for (var i = 0; i < elements.length; i++) {
        elements[i].setAttribute("fill", "remove");
        elements[i].endElement();
      }
    }

    /* ]]> */
  </script>
</head>
<body>
  <h1>Scalable Vector Graphics (SVG) - SVG Animations</h1>

  <svg xmlns="http://www.w3.org/2000/svg" width="600px" height="400px">
    <rect x="10" y="10" width="100" height="100">
      <!-- begin="indefinite" allows us to start the animation from script -->
      <animate attributeName="x" begin="indefinite" dur="1s" from="10" to="300" fill="freeze" />
    </rect>

  </svg>

  <button onclick="go();" type="button">Go</button>
  <button onclick="reset();" type="reset">Reset</button>

</body>
</html>