Create A Svg Line Animation
Requirements: To create a svg line animation, you need to know basic html & css.
Now we need a svg path. so let's just take a straight path for now.
<svg width="200" height="100">
<path d="M 0 50 H 200" stroke="#282828" stroke-width="2" />
</svg>Here, we are creating a svg with a width of 200px and a height of 100px, and what is M & H ?
- we are going 50px down from the top by changing y-axis.
- M is used to move the pen to the point, in this case it is 0 50 (x y).
- H is used to draw a horizontal line from the current position (Which is M 0 50 in our case) to the given coordinates 100 50 (x y), which is straight line to x-axis.
Now Let's see how this line looks like.
So, we have a line now.
Let's try to animate this line - with a light moving from left to right, To animate this we need to use few things.
- A circle tag
- A path mask
Let's start with a circle tag.
<circle cx="50%" cy="50%" r="20" fill="white" />Here, we are creating a circle with a radius of 20px, and a fill of white.
Now, let's see how this circle looks like.
Amazing - we got a cute circle right there in middle beacuse we are moving circle -50% from x-axis and -50% from y-axis - from original 0 0 position.
Now, we need to create a path mask. here is the code for that.
<mask id="circle-path-mask">
<path d="M 0 50 H 200" stroke="white" stroke-width="2" />
</mask>Did you notice something similar to our line code? Yes, we are using the same path which we used to create a line - but this time it's a mask and it's invisible.
Note: make sure to define the mask in defs tag.
Let's combine all code and see how it looks like.
<svg width="200" height="100">
<path d="M 0 50 H 200" stroke="#282828" stroke-width="2" />
<circle cx="50%" cy="50%" r="20" fill="white" mask="url(#circle-path-mask)" />
<defs>
<mask id="circle-path-mask">
<path d="M 0 50 H 200" stroke="white" stroke-width="2" />
</mask>
</defs>
</svg>Here, we are using the path id circle-path-mask to mask the circle. and we are using the url() function to reference the mask.
Woah - we got a circle with mask applied to it.
Now, Our last step is to animate the circle, from left to right. we will be using CSS to animate the circle.
.animate-circle-line {
animation: animate-circle-line 2s linear infinite;
}
@keyframes animate-circle-line {
0% {
transform: translateX(0);
}
100% {
transform: translateX(100%);
}
}Now lets apply this class to our circle tag.
<svg width="200" height="100" viewBox="0 0 200 100">
<path d="M 0 50 H 200" stroke="#282828" stroke-width="2" />
<g className="animate-circle-line">
<circle cx="0" cy="50" r="20" fill="white" mask="url(#circle-path-mask)" />
</g>
<defs>
<mask id="circle-path-mask">
<path d="M 0 50 H 200" stroke="white" stroke-width="2" />
</mask>
</defs>
</svg>
<style>{`
.animate-circle-line {
animation: animate-circle-line 2s linear infinite;
}
@keyframes animate-circle-line {
0% {
transform: translateX(0);
}
100% {
transform: translateX(100%);
}
}
`}</style>