A Trick That Makes Drawing SVG Lines Way Easier
When drawing lines with SVG, you often have a element with a
stroke
. You set a stroke-dasharray
that is as long as the path itself, as well as a stroke-offset
that extends so far that you that it’s initially hidden. Then you animate the stroke-offset
back to 0
so you can watch it “draw” the shape.
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:
<path d="M66.039,133.545 ... " pathLength="1" />
That doesn’t do anything by itself (as far as I know). It’s not like that only draws part of the path — it still draws the whole thing like as if you did nothing, only now the “math” of the path length is based on a value of 1.
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.
The post A Trick That Makes Drawing SVG Lines Way Easier appeared first on CSS-Tricks.