Use CSS Animation to Draw SVG

Jhey Tompkins
InstructorJhey Tompkins
Share this video with your friends

Social Share Links

Send Tweet

Using stroke-dashoffset and stroke-dasharray, we're able to make SVG strokes look as if they are drawn using CSS animation.

Jhey Tompkins: [0:00] We have our naughts and crosses, but it'd be neat if we could animate them in as if they were being drawn.

[0:04] 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.

[0:19] 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.

[0:35] 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 .

[1:02] 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.

[1:20] 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.

[1:39] [crosstalk to]

Jhey: [1:39] that works to make it seem as if the SVG is being drawn.