Let's go
Drawing an SVG path couldn't be easier, especially with the pathLength
attribute. If you are supporting older browsers, click through to the link to see if your browser is supported.
So let's get an SVG path that we can draw.
Check out the Codepen here which has the SVG included.
The first trick is to add the pathLength
property to our path
.
<path ..... pathLength="1" />
Doing this makes the animation much easier as we now know the length (i.e. 1). Before you had to calculate the length which was a massive pain!
The next thing we need to do is use stroke-dasharray
and stroke-dashoffset
. We will set both to 1, this essentially makes our SVG disappear so we can draw it. I don't want to delve into these but you can read about stroke-dashoffset
here and stroke-dasharray
here. Just know you can set pathLength
on any path
that you want to draw so once you set it to 1
you can set stroke-dasharray
and stroke-dashoffset
to 1
everytime!! 😇
So in the CSS panel add the following:
svg path {
stroke-dasharray: 1;
stroke-dashoffset: 1;
}
So the heart has disappeared, that is what we want as we are about to draw it back.
We need to create an animation that will animate stroke-dashoffset
back to 0.
@keyframes draw {
from {
stroke-dashoffset: 1;
}
to {
stroke-dashoffset: 0;
}
}
One last thing, just add the draw
animation to our path.
svg path {
stroke-dasharray: 1;
stroke-dashoffset: 1;
animation: draw 5s linear alternate infinite;
}
Our animation is infinite
and also will alternate
so it will draw back and forth.
Believe it or not but we are now done. You should have the following:
Complete pen is here.
Conclusion
Any questions on the above, feel free to contact me on my socials!
Top comments (0)