In this short tutorial, I'll demonstrate how to animate the paths of any SVG similar to the animation shown in this gif (the animation is slowed down in the gif :/ ).
There are a few ways to create SVGs and by the end of this tutorial, you'll get the idea of how to apply this effect to other variants too to create nice effects with just a few lines of code.
Before we move on, remember you can implement your websites or landing pages with or without coding on DoTenX for free. Make sure to check it out and even nominate your work to be showcased.DoTenX is open-source and you can find the repository here: github.com/dotenx/dotenx.
We start by creating add our SVG element to the page:
<svg width="200px" height="200px" viewBox="0 0 60 60" preserveAspectRatio="xMidYMid meet" stroke="gray" stroke-width="1" class="svgAnimate">
<path fill="none" d="M20,0 L20,20" />
<path fill="none" d="M20,20 L40,20" />
<path fill="none" d="M40,20 a20,20 0 0,1 -20,20" />
<path fill="none" d="M20,40 a20,20 0 0,1 -20,-20" />
<path fill="none" d="M0,20 a20,20 0 0,1 20,-20" />
</svg>
This is a simple SVG element with a 200px width and 200px height.
The minimum x-coordinate, y-coordinate, width, and height are represented by the numbers in the viewBox
property, which determines how the SVG's contents should be resized to fit inside the specified dimensions.
Also, the value "xMidYMid meet" denotes that the SVG will be centred and resized to suit the specified dimensions while keeping its aspect ratio.
Now we need the following styles and animation:
.path {
stroke-dasharray: 100;
stroke-dashoffset: 100;
animation: progress 2s linear forwards;
}
@keyframes progress {
to {
stroke-dashoffset: 0;
}
}
The stroke-dasharray
attribute specifies the arrangement of dashes and gaps used to draw the shape's outline.
The stroke-dashoffset
attribute defines an offset on the related dash stroke-dasharray's
rendering.
We have created a simple animation named progress with a single keyframe that simply removes the gap created in the stroke-dasharray
due to the stroke-dashoffset
.
Try yourself: What does happen if we just apply the class path to all the
path
children of thesvg
?
In order to execute the animations one after another we use this javascript code:
const el = document.querySelector(".svgAnimate");
for (let i = 0; i < el.children.length; i++) {
el.children[i].style.animationDelay = `${i * 0.25}s`
el.children[i].classList.add('path')
}
In this simple code, we just find the svg element and add a delay to each path
element based on its order in the list of children. This is different from setting a constant animation delay for all the elements.
Top comments (3)
Great đź‘Ź
Thanks! I'm glad you find it helpful.
You can also use this to do border animation with little bit of imagination