Search code examples
javascriptcsssvgsvg-animate

Animate SVG on hover - Make a smile from dots on hover


I have an SVG file with dots in in straight line. What I want to achieve is when a user hover on the svg file the dots to become a smile like the attached image.

The transition need to be smooth.

What is the best approach here? Can I do it with only css or I should use js also?

enter image description here

Thanks


Solution

  • With a SMIL animation, this is possible without any scripting. It morphs the cubic bezier path from straight to curved and back. The animation is triggered by mouseover and mouseout events over a transparent rectangle that sits on top of the line.

    The line itself uses the combination of two little tricks: You can set a pathLength as an attribute, so that stroke-dasharray then computes dash lengths according to it. And for a stroke-dasharray: 0 1 in combination with stroke-linecap, the zero-length dashes are displayed as dots with the stroke width as their diameter. Just play with the values for pathLength and stroke-width to change the distance of the dots and their size.

    #line {
      fill: none;
      stroke: black;
      stroke-width: 4;
      stroke-dasharray: 0 1;
      stroke-linecap: round;
    }
    #overlay {
      opacity: 0;
    }
    <svg viewBox="0 0 100 100" width="150">
      <path id="line" d="M 10 50 C 35 50 65 50 90 50" pathLength="15">
        <animate attributeName="d" begin="overlay.mouseover" dur="0.3s"
                 fill="freeze" restart="whenNotActive"
                 from="M 10 50 C 35 50 70 50 90 50"
                 to="M 15 30 C 20 70 80 70 85 30"/>
        <animate attributeName="d" begin="overlay.mouseout" dur="0.3s"
                 fill="freeze" restart="whenNotActive"
                 from="M 15 30 C 20 70 80 70 85 30"
                 to="M 10 50 C 35 50 65 50 90 50"/>
      </path>
      <rect id="overlay" width="100%" height="100%" />
    </svg>