Search code examples
htmlcsssvgsvg-animate

Svg fill animation for the given path


I am trying to animate an arrow from left to right.The code of my arrow's path is given below:

<svg id="svg_circle" width="100%" height="100%" viewBox = '0 0 450 400'> 
    <g transform = "translate(0,0)"> 
      <path class="path" stroke="#F0F0F0" fill="#fff" stroke-width="1" opacity="1" d="m34.97813,21.70979l-33.55223,0.47088l-0.0394,-13.57138l34.2665,-0.47295l-0.0208,-7.14282l14.50618,14.42226l-14.95643,15.04345l-0.20382,-8.74944z" id="svg_1"> 
          <animate id="project_anim1" attributeName="fill" from="#fff" to="#4DAF4C" begin="1s" dur="1s" fill="freeze" repeatCount="1"></animate>
      </path>
    </g>
</svg>

The above is the svg path content of my arrow.

Kindly anyone help me how to fill the path from left to right. Waiting for quick response


Solution

  • You can do this by just animating the <stop>s in a <linear gradient>.

    <svg id="svg_circle" width="100%" height="100%" viewBox = '0 0 450 400'> 
    
      <defs>
        <linearGradient id="left-to-right">
          <stop offset="0" stop-color="#4DAF4C">
            <animate dur="2s" attributeName="offset" fill="freeze" from="0" to="1" />
          </stop>
          <stop offset="0" stop-color="#fff">
            <animate dur="2s" attributeName="offset" fill="freeze" from="0" to="1" />
          </stop>
          
        </linearGradient>
      </defs>
    
      <path class="path" stroke="#F0F0F0" fill="url(#left-to-right)" stroke-width="1" opacity="1" d="m34.97813,21.70979l-33.55223,0.47088l-0.0394,-13.57138l34.2665,-0.47295l-0.0208,-7.14282l14.50618,14.42226l-14.95643,15.04345l-0.20382,-8.74944z" id="svg_1" />
    </svg>

    How this works is that we have a linear gradient representing an abrupt change from green to white. The <animation> elements move the position, of that abrupt change, from the left of the arrow (offset=0) to the right (offset="1").

    Note that SVG <animate> elements will not work in IE. If you need to support IE, you will need to use the FakeSmile library or use a different method (such as a JS animation library).