When drawing lines with SVG, you often have a
Figuring out the length of the path is the trick, which fortunately you can do in JavaScript by selecting the path and doing pathEl.getTotalLength(). It’ll probably be some weird decimal. A smidge unfortunate we can’t get that in CSS, but c’est la vie.
Here’s the trick!
You don’t have to measure the length of the path, because you can set it.
So you do like:
Now we can set the stroke-dasharray to 1, and animate the offset in CSS!
.path {
stroke-dasharray: 1;
stroke-dashoffset: 1;
animation: dash 5s linear alternate infinite;
}
@keyframes dash {
from {
stroke-dashoffset: 1;
}
to {
stroke-dashoffset: 0;
}
}
Which works:
See the Pen
Basic Example of SVG Line Drawing, Backward and Forward by Chris Coyier (@chriscoyier)
on CodePen.
High five to Adam Haskell who emailed me about this a few months back.
Hey, speaking of SVG line drawing: Lemonade made a landing page for their 2019 charity that uses scroll-triggered SVG line drawing up and down the entire page. They did a behind-the-scenes look at it, which I always appreciate.