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>
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.
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
.
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;
}
}
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! β£οΈ
Top comments (1)
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
let's dance with pixels using animations
Rahul Jain γ» Jul 4 γ» 2 min read