For those who are not familiar with the basic fundamentals of SVG, you can see the article “Futa Web Development Team”

SVG Animation Basics

stroke-dasharray

This property is used to define the dot and dash so let’s see what happens

    <svg width="100" height="100">
      <path d="M2 2 L98 2" stroke="pink" stroke-width="4" />
      <path
        d="M2 10 L98 10"
        stroke="pink"
        stroke-width="4"
        stroke-dasharray="10px"
      />
    </svg>
Copy the code

For the second line, set the property stroke-Dasharray =”10px”. You can see that both the solid line and the dotted line are 10px apart.

This property can also be set to multiple values, so let’s go ahead and try to create a third line and set the property to stroke-Dasharray =”10px 5px”

We find that the first value 10px is the length of the solid line, the second value 5px is the length of the dotted line, and the rest is cyclic.

stroke-dashoffset

This attribute is used with the Stroke-Dasharray attribute and defines the offset for the dot and dash. Let’s set stroke-DashoffSet =”5px” for the third line and see what happens:

We find that the third line is offset by 5px to the left, or by the right if it is set to a negative value

SVG animation

So far, we’ve looked at Stroke-Dasharray and Stroke-Dashoffset, and we’ve seen the basics of how to use them, and with the Transition animation we can achieve some unexpected effects

Draw line transition effect

Key points to achieve the effect of line drawing transition:

  • stroke-dasharrayIs set to the length of the line
  • stroke-dashoffsetThe value of is also set to a straight line, offsetting the solid part of the line out of sight
<style>
    path {
      transition: stroke-dashoffset 0.3 s;
    }
    svg:hover #drawLine {
      stroke-dashoffset: 0;
    }
</style>
      <path
        id="drawLine"
        d="M2 40 L98 40"
        stroke="pink"
        stroke-width="4"
        stroke-dasharray="96px"
        stroke-dashoffset="96px"
      />
Copy the code

Loading waiting animation

Key points to achieve:

  • stroke-dasharrayIs set to the perimeter of the SVG circle
  • stroke-dashoffsetThe value of is also set to the perimeter of the SVG circle, offsetting the solid part of the SVG circle out of sight
  • Add a rotation animationrotete(360deg)
<style>
    #circle {
      stroke-dasharray: 239px;
      stroke-dashoffset: 239px;
      animation: rotate 1s linear infinite;
      transform-origin: center;
    }
    @keyframes rotate {
      0% {
        stroke-dashoffset: 239px;
      }
      100% {
        stroke-dashoffset: 0px;
        transform: rotate(360deg); }}</style>

    <svg width="100" height="100">
      <circle
        id="circle"
        cx="50"
        cy="50"
        r="38px"
        stroke-width="6px"
        stroke="pink"
        fill="none"
      />
    </svg>
Copy the code