GSAP

Language: JavaScript

Animation

GSAP was created by Jack Doyle (GreenSock) in the mid-2000s to provide a professional-grade animation library that works consistently across browsers. It has become widely adopted in web development for animations ranging from simple UI transitions to complex interactive motion graphics.

GSAP (GreenSock Animation Platform) is a powerful JavaScript library for creating high-performance animations on the web. It supports complex sequencing, tweening, and timeline-based animations with smooth performance across all major browsers.

Installation

npm: npm install gsap
yarn: yarn add gsap

Usage

GSAP provides `gsap.to()`, `gsap.from()`, `gsap.fromTo()`, and `gsap.timeline()` methods to animate DOM elements, canvas, SVG, and more. Animations can be chained, sequenced, and controlled with easing, duration, delays, and callbacks.

Simple tween

import { gsap } from 'gsap';
gsap.to('.box', { x: 100, duration: 1 });

Animates the element with class `box` 100px to the right over 1 second.

Tween from initial state

gsap.from('.box', { opacity: 0, y: -50, duration: 1 });

Animates the element from opacity 0 and y-position -50px to its current state.

Timeline sequencing

const tl = gsap.timeline({ repeat: 1, yoyo: true });
tl.to('.box', { x: 100, duration: 1 })
  .to('.box', { y: 50, duration: 1 })
  .to('.box', { rotation: 360, duration: 1 });

Creates a timeline to sequence multiple animations with repeat and yoyo effects.

Animating multiple elements

gsap.to('.box', { x: 200, stagger: 0.2, duration: 1 });

Animates multiple elements with the `box` class, staggering their start times by 0.2 seconds.

Scroll-triggered animation

import { ScrollTrigger } from 'gsap/ScrollTrigger';
gsap.registerPlugin(ScrollTrigger);
gsap.to('.box', {
  x: 300,
  scrollTrigger: {
    trigger: '.box',
    start: 'top center',
    end: 'bottom 100px',
    scrub: true
  }
});

Animates an element based on scroll position using the ScrollTrigger plugin.

SVG animation

gsap.to('#circle', { strokeDashoffset: 0, duration: 2 });

Animates an SVG circle’s stroke using strokeDashoffset for a drawing effect.

Error Handling

gsap is not defined: Ensure GSAP is imported correctly, e.g., `import { gsap } from 'gsap';` or included via CDN.
Cannot animate null element: Ensure the DOM element exists and is accessible before animating it.
Plugin not registered: For GSAP plugins, make sure to import and register them, e.g., `gsap.registerPlugin(ScrollTrigger);`

Best Practices

Use timelines for sequencing multiple animations to maintain control and readability.

Use hardware-accelerated properties like transforms for smoother animations.

Leverage GSAP plugins (ScrollTrigger, Draggable, MotionPathPlugin) for advanced interactivity.

Keep animations performant by limiting unnecessary DOM manipulations.

Use easing functions to create natural motion.