Create Svg Line Animation

Learn to create 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 ?

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.

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.

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.

Damn - its moving? but it's not moving from left to right. its moving from center to right.

To Fix this lets change -50% to 0% from cx attribute from our circle tag.

Hehe - it's moving from left to right. That's it.