GSAP SVG Stroke Dash Animation

GSAP Animation Preview: SVG Stroke Draw

Code Snippet


// components/GSAP_Stroke.tsx
import { useEffect, useRef } from 'react';
import gsap from 'gsap';

export const GSAP_Stroke = () => {
  const pathRef = useRef<SVGPathElement | null>(null);

  useEffect(() => {
    const length = pathRef.current?.getTotalLength() || 0;
    gsap.fromTo(
      pathRef.current,
      { strokeDasharray: length, strokeDashoffset: length },
      { strokeDashoffset: 0, duration: 1.4, ease: 'power2.out' }
    );
  }, []);

  return (
    <svg width="100" height="100">
      <path
        ref={pathRef}
        d="M10 10 L90 90"
        stroke="#111"
        strokeWidth={2}
        fill="none"
      />
    </svg>
  );
};

Explanation

  • strokeDasharray / strokeDashoffset: Used to simulate drawing of paths.
  • getTotalLength(): Returns the total length of the SVG path.
  • gsap.fromTo: Animates from fully hidden stroke to visible.
  • ease: Smooth drawing motion via power2.out.
  • Great for logo draws, signatures, or animated outlines.