GSAP SVG Morph Animation

GSAP Animation Preview: SVG Morph

Code Snippet


// GSAP Morph Component (Scoped)
import { useRef, useEffect } from "react";
import gsap from "gsap";
import { MorphSVGPlugin } from "gsap/MorphSVGPlugin";
gsap.registerPlugin(MorphSVGPlugin);

export const GSAP_Morph = () => {
  const ref = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    if (!ref.current) return;

    const ctx = gsap.context(() => {
      const path = ref.current!.querySelector('path');
      if (!path) return;

      const tl = gsap.timeline({ repeat: -1, yoyo: true });
      tl.to(path, {
        duration: 1.6,
        morphSVG: "M10 20 Q 95 80 180 20 T 350 20",
        ease: "power1.inOut",
      });

      return () => tl.kill();
    }, ref);

    return () => ctx.revert();
  }, []);

  return (
    <div ref={ref}>
      <svg width="400" height="180" viewBox="0 0 400 100" fill="none">
        <path
          d="M10 80 Q 95 10 180 80 T 350 80"
          stroke="#22c55e"
          strokeWidth="4"
          fill="none"
        />
      </svg>
    </div>
  );
};

Explanation

  • gsap.context: Scopes the animation so it can be safely rerun.
  • MorphSVGPlugin: Smoothly morphs one SVG path to another.
  • repeat / yoyo: Loops the morph infinitely back and forth.
  • Clicking "Run Again" remounts the component and triggers the morph animation again.