I'm trying to animate the line extension.

I already have this solution in css , but I need to do it in javaScript , because this is the only way to get the length of the path that I need to implement the animation.
I think I came very close to the solution, but it does not work! Any ideas?

Below is my code. As you can see, I get the length of the path and assign a strokeDashArray value to this length.
This means that the line will be dashed, but the dotted line will fill 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 line drawing.

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

Note translator

I chose this post for translation for two reasons: since I often encountered type questions, how to calculate the length of a line using JS and draw it. Secondly, the method of hatching animation using JS seemed interesting to me. This technique, in my opinion, can be used in interactive web design. For example, hatching checkboxes, instead of standard check marks, etc.

1 answer 1

Code:

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

Basically equivalent to:

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

Because the loop breaks through all its iterations, not allowing the browser to refresh the page.

To get around this, take one step in a loop, and then call setTimeout() so that the browser returns to us a bit so that 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) { //На ΠΊΠ°ΠΆΠ΄ΠΎΠΌ шагС ΠΌΡ‹ ΡƒΠΌΠ΅Π½ΡŒΡˆΠ°Π΅ΠΌ смСщСниС Ρ‚ΠΈΡ€Π΅ len -= 10; if (len < 0) len = 0; element.style.strokeDashoffset = len; //Нам Π½ΡƒΠΆΠ½ΠΎ ΠΏΡ€Π΅ΠΊΡ€Π°Ρ‚ΠΈΡ‚ΡŒ Ρ†ΠΈΠΊΠ», ΠΊΠΎΠ³Π΄Π° Π΄Π»ΠΈΠ½Π° достигнСт `0` if (len > 0) { // Π‘Π΄Π΅Π»Π°Ρ‚ΡŒ Π΅Ρ‰Π΅ ΠΎΠ΄ΠΈΠ½ шаг 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>