Using stroke-dashoffset and stroke-dasharray, we're able to make SVG strokes look as if they are drawn using CSS animation.
Duration
2 min
Access
Free
Transcript
Available
Using stroke-dashoffset and stroke-dasharray, we're able to make SVG strokes look as if they are drawn using CSS animation.
Video Transcript
Jhey Tompkins: We have our naughts and crosses, but it'd be neat if we could animate them in as if they were being drawn.
Let's start by animating our circle. To do this we're going to use the stroke-dasharray attribute. We're going to set this to a value of 200. Then we're going to use a stroke-dashoffset attribute, and we're going to set that also to 200.
What stroke-dasharray does is it sets a stroke-dash on our element. Here we're saying a stroke-dash of 200. Because the offset is 200, we don't see anything. If we set that dash offset to 100, we'll see a half circle.
To animate the circle being drawn we're going to start by defining a draw-speed. Let's set that to .2 seconds. Then we're going to define an animation for our circle elements. Let's do animation draw var(--draw-speed) for the duration, ease-in for the timing-function. Then let's define those keyframes draw as to and then stroke-dashoffset .
If we try out our demo, our circle animates in but then disappears. We can use animation-fill-mode to fix this. Let's use the value of animation-fill-mode both because we anticipate that we might use an animation delay. Now our circle reappears. If we try again with a different circle, we can see it animate in.
We can also apply the same animation to the paths of our cross. Then we define the same attributes for the paths of our cross. Let's start with stroke-array and give it a value of 100. Then let's define a stroke-offset also of 100. We apply that to both paths.
[crosstalk to]
Jhey: that works to make it seem as if the SVG is being drawn.
Duration
2 min
Access
Free
Transcript
Available
Course lesson
Use CSS Animation to Draw SVG
Using stroke-dashoffset and stroke-dasharray, we're able to make SVG strokes look as if they are drawn using CSS animation.