Change strokeDashoffset of a SVG line in a for loop

前端 未结 1 1516
攒了一身酷
攒了一身酷 2021-02-15 00:47

I\'m trying to animate a line expanding. I already have it in css, but I need to do it in javaScript, because that is the only way I can get the lenght of the path, which I need

1条回答
  •  梦谈多话
    2021-02-15 01:16

    The code:

    function animateRoute (e) 
    {
       e.style.strokeDashoffset = e.style.strokeDashoffset - 100;
    }
    
    for (i = 0; i < 100; i++)
    {
       animateRoute(element);
    }
    

    Is basically equivalent to

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

    Because the loop whips through all its iterations without giving the browser a chance to update the page.

    To get around that, do one step in the loop and then call setTimeout() to tell the browser to come back to us in a little bit so we can do the next iteration.

    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);
    
      
        
      
    

    0 讨论(0)
提交回复
热议问题