Change the strokeDashoffset of an SVG string in a for loop

I'm trying to animate a line expanding. I already have this in css, but I need to do this in javaScript, because this is the only way to get the path length that I need. I think I'm very close, but it does not work! Any ideas?

Below is my code. As you can see, I get the path length and give it a strokeDashArray of that length. This means that the line will be split, but the dash fills the entire line. The trick is to decrease the strokeDashoffset value, because it determines where the dash begins. Therefore, if it also starts with pathLength, the line will be completely invisible, and decreasing the value will show the path.

I know that it is possible btw :) As already mentioned, I already have work in css.

var element = document.getElementById("animpath");
var pathLength = element.getTotalLength();

element.style.strokeDasharray = pathLength;
element.style.strokeDashoffset = pathLength;

function animateRoute (e) 
{
e.style.strokeDashoffset = e.style.strokeDashoffset - 100;
}

for (i = 0; i < 100; i++)
{
animateRoute(element);
}

Thanks in advance!

+4
1

:

function animateRoute (e) 
{
   e.style.strokeDashoffset = e.style.strokeDashoffset - 100;
}

for (i = 0; i < 100; i++)
{
   animateRoute(element);
}

e.style.strokeDashoffset = e.style.strokeDashoffset - 10000;

, .

, , setTimeout(), , .

var element = document.getElementById("animpath");
var pathLength = element.getTotalLength();

element.style.strokeDasharray = pathLength;
element.style.strokeDashoffset = pathLength;

function animateRoute(e, len) 
{
  // Each step we decrement the dash offset
  len -= 10;
  if (len < 0)
    len = 0;  // clamp to minimum 0

  element.style.strokeDashoffset = len;

  // We need to stop looping when the length gets to 0
  if (len > 0) {
    // Do another step
    setTimeout(function() { animateRoute(e, len); }, 10);
  }
}

animateRoute(element, pathLength);
<svg viewBox="-10 -10 420 120">
  
    <path id="animpath" d="M 0 0 L 400 10 0 20 400 30 0 40 400 50 0 60 400 70 0 80 400 90 0 100"
          stroke="black" stroke-width="3" fill="none"/>
  
</svg>
+4

All Articles