DEV Community

Maxime Guilbert
Maxime Guilbert

Posted on • Updated on

How to animate SVG line

To add some dynamism to your HTML page, we can add some animations, especially on icons. So we will do a simple SVG line animation to try it.

Starting slow

First, let's just draw a circle. It will be our base.

Add an animation

To animate the circle, we will use the next properties :

  • stroke-dasharray: This defines the line dash size.
  • stroke-dashoffset: This defines the offset between the start of the line and the first dash.

Example

Then the animation is simple. We will create a dash that measures the entire line and add an offset of the same length. Then with the animation, we will reduce the offset size, and the drawing will appear.

But how can we know the exact size of a line?

With a little bit of javascript, we can retrieve this information.

pathElement.getTotalLength()
Enter fullscreen mode Exit fullscreen mode

So if we add this information with a javascript loop, we are able to create our first animation!

Hooray! We did it!

A little bit more!

Here we've done the first step. Now, if you want to do a more complex animation, you can add other lines to draw a planet icon.

And then you just have to add multiple classes to delay some parts of the animation to have a cool SVG line animation.


I hope you've enjoyed this post! If you have some other tips to share, don't hesitate to post it in the comments, or create your own post and share here the link! :)

Top comments (0)