DEV Community

Cover image for Simple SVG drawing effect with `stroke-dasharray` & `stroke-dashoffset`
Paul Ryan
Paul Ryan

Posted on • Originally published at paulryancodes.com

Simple SVG drawing effect with `stroke-dasharray` & `stroke-dashoffset`

If you prefer video format you can head here.

Hey everyone, I hope you are having a great day!

Today I am going to show you how to do a simple SVG drawing effect with stroke-dasharray and stroke-dashoffset.

So take the following SVG path:

<svg width="400" height="100" viewBox="0 0 400 100">
  <path 
        d="m 0 0 h 300" 
        stroke="black" 
        pathLength="10"
        stroke-width="15"></path>
</svg>

Visually, that gives us:
The SVG Path

So this has a stroke of black which is a continuous black line, we can split this up into dashes using stroke-dasharray. Our path has a pathLength of 10, if we set stroke-dasharray to 2, that means we will split our path into dashes of 2.

This is how the path will look.
Dash & Path

So each dash has width of 2 and each gap has a width of 2 so 10/2 = 5.

If we wanted to start on a gap rather than dash, we can use the stroke-dashoffset attribute and set it to a value of 2.
Path starting with a GAP

Cool, setting the stroke-dashoffset to the same value as stroke-dasharray will offset the gap or dash.

Using this knowledge, we can create a drawing effect. To achieve this, the first thing we do is set stroke-dasharray to the same length of the path which is 10. Visually this will make no change, but we can use stroke-dashoffset to start on a gap, like above we simply set this to the same value of stroke-dasharray which is 10.

<svg width="400" height="100" viewBox="0 0 400 100">
  <path pathLength="10" d="m 0 0 h 300" stroke="black" stroke-width="15"></path>
</svg>
path {
  stroke-dasharray: 10;
  stroke-dashoffset: 10;
}

This will render a blank screen as we are starting on a gap that is the same length of our entire path.

Using some basic CSS, we can create a drawing animation, we simply want to animate the stroke-dashoffset from the value of 10 to the value of 0.

path {
  stroke-dasharray: 10;
  stroke-dashoffset: 10;
  animation: draw 2s ease forwards;
}

@keyframes draw {
  from {
    stroke-dashoffset: 10;
  }

  to {
    stroke-dashoffset: 0;
  }
}

This gives us the following:
Line Animation

Nice!

Here is the Codepen you can play around with or fork.

Any questions on the above, feel free to contact me on my socials! ❣️

πŸ’‚β€β™‚οΈ Insta πŸ‘€ Twitter πŸ’¬ Github πŸ’­ LinkedIn πŸ’₯ Youtube πŸ“­ Website

Top comments (1)

Collapse
 
rahuldkjain profile image
Rahul Jain

Simply Cool. I really love the idea of using SVGs as it takes hell lot of less memory.

I am learning SVG Animations and you won't regret to check this out