GSAP (GreenSock Animation Platform)

repository·master·Indexed 12 days ago

https://github.com/greensock/gsap

A high-performance, framework-agnostic JavaScript animation library for animating CSS, SVG, Canvas, WebGL, and generic objects. Version 3.15.0 features advanced sequencing, a robust plugin ecosystem including ScrollTrigger, Draggable, and CustomBounce, and a dedicated @gsap/react package with the useGSAP() hook for automated cleanup in React applications.

Tokens
36.7K
Snippets
153
Records
176
Agent score
98%

What's inside GSAP

  1. Overview of GSAP Core Capabilities

    master

    GSAP is a framework-agnostic JavaScript animation library designed for high-performance property manipulation.

    Key Features:

    • High Performance: Optimized to update values with extreme accuracy, significantly faster than jQuery.
    • Versatility: Animates CSS, SVG, Canvas, WebGL, colors, strings, and generic JavaScript objects.
    • Zero Dependencies: Works independently in any environment.
    • Advanced Sequencing: Provides tight control over complex animation timelines.
    • Responsive Design: Includes gsap.matchMedia() for building accessibility-friendly and responsive animations.
    • Plugin Ecosystem: Supports advanced effects like scrolling (ScrollTrigger), morphing (MorphSVGPlugin), text splitting (SplitText), motion paths (MotionPathPlugin), and FLIP animations.
  2. Manage animation cleanup with gsap.context

    master

    gsap.context(func, scope) is a powerful tool for managing animations, especially within component-based frameworks like React or Vue. It allows you to group animations together so they can be reverted or killed all at once.

    Key Features

    • Scoping: If a scope is provided, all selectors used inside the context function will be scoped to that element.
    • Reversion: Calling context.revert() will undo all animations, timelines, and even matchMedia queries created within that context.
    • Cleanup: It tracks all tweens and timelines created inside it, making it easy to prevent memory leaks or animation artifacts when a component unmounts.

    Usage Pattern

    const ctx = gsap.context(() => {
      // All animations created here are tracked by ctx
      gsap.to('.box', { x: 100 });
    }, scopeElement);
    
    // Later, to clean up everything:
    ctx.revert();
    import { gsap } from 'gsap';
    
    const container = document.querySelector('#container');
    const ctx = gsap.context(() => {
      // Animations are scoped to #container
      gsap.to('.box', { rotation: 360 });
    }, container);
    
    // Clean up everything when done
    ctx.revert();
  3. Use GSAP with React

    master
    For React applications, it is recommended to use the @gsap/react package. This package provides the useGSAP() hook, which serves as a drop-in replacement for useEffect() or useLayoutEffect(). The primary benefit of useGSAP() is that it automates animation cleanup tasks, preventing memory leaks and unexpected behavior during component unmounting.
  4. Register plugins with gsap.registerPlugin

    master

    To use GSAP plugins (like ScrollTrigger, Draggable, etc.), you must register them using gsap.registerPlugin(). This ensures that the plugins are correctly initialized and can interact with the core engine.

    import { gsap } from 'gsap';
    import { ScrollTrigger } from 'gsap/ScrollTrigger';
    
    gsap.registerPlugin(ScrollTrigger);
    import { gsap } from 'gsap';
    import { ScrollTrigger } from 'gsap/ScrollTrigger';
    
    // Always register plugins before using them
    gsap.registerPlugin(ScrollTrigger);
  5. Import and Register GSAP Plugins

    master

    When using GSAP via NPM, you can import the core library and specific plugins individually. After importing, you must register the plugins using gsap.registerPlugin() to ensure they function correctly within the GSAP ecosystem.

    // typical import
    import gsap from "gsap";
    
    // get other plugins:
    import ScrollTrigger from "gsap/ScrollTrigger";
    import Flip from "gsap/Flip";
    import Draggable from "gsap/Draggable";
    
    // or all tools are exported from the "all" file (excluding members-only plugins):
    import { gsap, ScrollTrigger, Draggable, MotionPathPlugin } from "gsap/all";
    
    // don't forget to register plugins
    gsap.registerPlugin(ScrollTrigger, Draggable, Flip, MotionPathPlugin); 
  6. Install GSAP via CDN

    master

    To use GSAP directly in the browser without a build step, include the following script tag in your HTML. This provides access to the core GSAP library.

    <script src="https://cdn.jsdelivr.net/npm/gsap@3.15/dist/gsap.min.js"></script>
  7. How Draggable snapping works

    master

    Draggable supports several ways to snap an element to specific positions during or after a drag interaction:

    • snap (Value/Array): Snaps the x or y position to a specific number or the closest value in an array.
    • liveSnap: Enables real-time snapping while the user is actively dragging. It can accept a configuration object containing points for 2D snapping.
    • snap.points: An array of {x, y} objects. Draggable will snap the element to the closest point within a specified radius.
    • snapX / snapY / snapXY: Specific functions to handle snapping for the X axis, Y axis, or both simultaneously.

    Snapping logic accounts for edgeResistance to ensure smooth movement near boundaries.

  8. Use GSAP CSS-specific shorthand properties

    master

    GSAP provides optimized shorthand properties for common CSS transformations to ensure better performance and smoother animations. These properties are available within the gsap.CSSProperties interface and can be used directly in tweens.

    Key GSAP-specific shorthands include:

    • Opacity: alpha (standard opacity) and autoAlpha (sets visibility: hidden when opacity is 0).
    • Rotation: rotate, rotateX, rotateY, rotateZ, rotation, rotationX, rotationY, and rotationZ.
    • Scale: scale, scaleX, and scaleY.
    • Skew: skew, skewX, and skewY.
    • Translation: x, y, z, translateX, translateY, translateZ, xPercent, and yPercent.
    • Origin: smoothOrigin and svgOrigin.
    // Example usage of GSAP shorthand properties
    gsap.to(".element", {
      x: 100,
      yPercent: 50,
      rotation: 360,
      scale: 1.5,
      autoAlpha: 0
    });
  9. Configure easing with ease strings and parameters

    master

    GSAP supports various easing functions that can be applied via strings or function objects.

    Common Easing Types:

    • Linear: No acceleration/deceleration.
    • Quad, Cubic, Quart, Quint, Strong: Power-based eases (e.g., power1.out, power2.inOut).
    • Elastic: Adds an elastic/spring-like effect. Can be parameterized: elastic.out(amplitude, period).
    • Back: Adds an overshoot effect. Can be parameterized: back.out(overshoot).
    • Bounce: Adds a bouncing effect.
    • Expo: Exponential acceleration/deceleration.
    • Circ: Circular easing.
    • Sine: Sine wave easing.
    • SteppedEase: Moves in discrete steps. Use SteppedEase.steps(n) where n is the number of steps.

    Parameterization: Many eases can be configured using parentheses in the string, such as back.out(2) or elastic.out(1, 0.3).

    // Using string-based easing with parameters
    gsap.to(".box", { x: 100, ease: "back.out(1.7)" });
    
    // Using SteppedEase
    gsap.to(".box", { x: 100, ease: "steps(5)" });
  10. How Draggable works with ScrollProxy

    master

    When autoScroll is enabled in Draggable, the plugin can use a ScrollProxy to manage scrolling of parent containers. A ScrollProxy wraps an element's contents into a new div (the "content") and uses translate3d or padding to simulate overscrolling. This allows Draggable to manipulate scrollTop or scrollLeft values to create a smooth dragging experience even when the target is constrained by scrollable parents.

    // Conceptual usage of ScrollProxy within Draggable context
    // ScrollProxy is used internally to handle overscroll and coordinate
    // translation with actual scroll positions.
  11. Use DrawSVGPlugin modifiers: live and nowrap

    master

    The drawSVG property supports two special modifiers to handle specific SVG behaviors:

    1. live: When added to the value (e.g., "20% 80% live"), the plugin continuously monitors the element's length. This is essential when using vector-effect="non-scaling-stroke", as the stroke length may change during window resizing or layout shifts.
    2. nowrap: When added to the value (e.g., "20% 80% nowrap"), it prevents the stroke from wrapping around the path if the calculated dash length is larger than the path length, which can sometimes cause visual artifacts in certain browsers.
    // Responsive drawing that adjusts to SVG scaling/resizing
    gsap.to("path", { drawSVG: "0% 100% live" });
    
    // Drawing without stroke wrapping artifacts
    gsap.to("path", { drawSVG: "10% 90% nowrap" });