Use CSS Animation to Draw SVG

Jhey Tompkins
InstructorJhey Tompkins
Share this video with your friends

Social Share Links

Send Tweet
Published 3 years ago
Updated 3 years ago

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.

egghead
egghead
~ 9 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today