Skip to content
Learni
Voir tous les tutoriels
Frontend

Comment maîtriser GSAP pour animations avancées en 2026

Read in English

Introduction

GSAP (GreenSock Animation Platform) est la bibliothèque JavaScript incontournable pour des animations web performantes et précises, surpassant CSS transitions en complexité et fluidité. En 2026, avec les navigateurs toujours plus exigeants en 120 FPS, GSAP excelle dans les timelines synchronisées, les triggers scroll intelligents et le morphing vectoriel, essentiels pour des sites immersifs comme les landing pages e-commerce ou portfolios interactifs.

Ce tutoriel avancé assume une maîtrise de JavaScript ES6+ et DOM. Nous construirons pas à pas des animations réelles : d'un tween basique à des séquences scroll complexes avec pinning et batching. Chaque exemple est autonome, testable en copiant-collant dans un fichier HTML. À la fin, vous saurez optimiser pour mobile (60 FPS stables) et scaler sur des apps React/Vue. Importance : 80% des sites top-tier utilisent GSAP pour réduire le bounce rate de 30% via micro-interactions engageantes. Prêt à bookmarker ? (142 mots)

Prérequis

  • Maîtrise de JavaScript ES6+ (async/await, destructuring).
  • Connaissances HTML/CSS avancées (Flexbox, Grid, transforms).
  • Navigateur moderne (Chrome 120+ pour tests).
  • Éditeur de code (VS Code avec extension Live Server).
  • Compte gratuit GreenSock pour bonus plugins (optionnel ici).

Tween basique avec easing personnalisé

demo-tween-basique.html
<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>GSAP Tween Basique</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.5/gsap.min.js"></script>
  <style>
    body { margin: 0; font-family: Arial; background: #f0f0f0; }
    .box { width: 100px; height: 100px; background: #4a90e2; margin: 50px auto; border-radius: 10px; }
  </style>
</head>
<body>
  <div class="box" id="box"></div>
  <script>
    gsap.to("#box", {
      duration: 2,
      x: 300,
      rotation: 360,
      scale: 1.5,
      backgroundColor: "#e94b3c",
      ease: "elastic.out(1, 0.3)"
    });
  </script>
</body>
</html>

Ce code charge GSAP via CDN et anime une boîte avec translation (x), rotation, scale et couleur via gsap.to(). L'easing 'elastic.out' simule un rebond naturel, idéal pour attirer l'attention sans surcharger le GPU. Piège : Oublier 'duration' rend l'animation instantanée ; testez toujours en throttlé CPU pour valider la fluidité.

Comprendre les tweens avancés

Les tweens GSAP transforment n'importe quelle propriété (CSS, SVG attributes, scroll) en 16ms par frame. Contrairement à CSS @keyframes rigides, GSAP calcule dynamiquement via requestAnimationFrame, supportant les callbacks onStart/onComplete. Analogie : un tween est comme un moteur de voiture – ease contrôle l'accélération/freinage. Ajoutez yoyo: true, repeat: -1 pour boucles infinies fluides.

Timeline avec séquences synchronisées

demo-timeline.html
<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>GSAP Timeline</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.5/gsap.min.js"></script>
  <style>
    body { margin: 0; font-family: Arial; background: linear-gradient(45deg, #667eea, #764ba2); height: 100vh; display: flex; align-items: center; justify-content: center; gap: 20px; }
    .box { width: 80px; height: 80px; border-radius: 50%; }
    #box1 { background: #ff6b6b; }
    #box2 { background: #4ecdc4; }
    #box3 { background: #45b7d1; }
  </style>
</head>
<body>
  <div class="box" id="box1"></div>
  <div class="box" id="box2"></div>
  <div class="box" id="box3"></div>
  <script>
    const tl = gsap.timeline({ repeat: -1, yoyo: true });
    tl.to("#box1", { duration: 1, x: 200, ease: "power2.inOut" })
      .to("#box2", { duration: 1, y: -150, rotation: 180, ease: "back.out(1.7)" }, "<0.5")
      .to("#box3", { duration: 1, scale: 2, ease: "bounce.out" }, "<");
  </script>
</body>
</html>

Une timeline orchestre plusieurs tweens avec positions relatives ('<' aligne au début du précédent). Ici, trois boîtes dansent en séquence/yoyo infini. Avantage : Contrôlez via tl.pause(), tl.reverse() pour interactions hover. Piège : Labels comme '>label' pour sauts ; sans repeatDelay, les loops collent.

Puissance des timelines pour UX complexes

Timelines gèrent des chorégraphies multi-éléments, parfaites pour hero sections. Utilisez stagger pour effets cascade : gsap.timeline().to('.items', {x: 100, stagger: 0.1}). Positions absolues (tl.to(..., {time: 2})) ou relatives ('+=1') scalent sur 100+ éléments sans lag.

Stagger avec fromTo et callbacks

demo-stagger.html
<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>GSAP Stagger</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.5/gsap.min.js"></script>
  <style>
    body { margin: 0; font-family: Arial; background: #000; color: white; padding: 50px; }
    .item { display: inline-block; padding: 20px 30px; margin: 10px; background: #333; border-radius: 10px; opacity: 0; transform: translateY(50px); }
  </style>
</head>
<body>
  <div class="item">Élément 1</div>
  <div class="item">Élément 2</div>
  <div class="item">Élément 3</div>
  <div class="item">Élément 4</div>
  <div class="item">Élément 5</div>
  <script>
    gsap.fromTo(".item", 
      { opacity: 0, y: 50 }, 
      {
        opacity: 1,
        y: 0,
        duration: 0.8,
        stagger: { amount: 1, from: "start", ease: "power2.out" },
        onComplete: () => console.log("Animation terminée"),
        onStart: () => console.log("Démarrage stagger")
      }
    );
  </script>
</body>
</html>

gsap.fromTo() définit état initial/final pour précision, stagger crée un délai séquentiel (ici 1s total pour 5 items). Callbacks loggent phases pour debug. Piège : stagger.grid() pour layouts 2D ; sans 'ease' par item, uniformité casse l'effet.

ScrollTrigger : animations contextuelles

Plugin gratuit ScrollTrigger lie animations au scroll, transformant sites statiques en expériences parallax. Triggers sur 'top center' pin/scrub pour reveal fluide. Analogie : comme un caméscope – start/end définissent le 'champ de vue'.

ScrollTrigger parallax et scrub

demo-scrolltrigger.html
<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>GSAP ScrollTrigger</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.5/gsap.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.5/ScrollTrigger.min.js"></script>
  <style>
    body { margin: 0; font-family: Arial; }
    section { height: 100vh; display: flex; align-items: center; justify-content: center; font-size: 3em; }
    #hero { background: linear-gradient(45deg, #ff9a9e, #fecfef); }
    #parallax { background: #667eea; color: white; }
    .parallax-img { width: 300px; height: 300px; background: #ff6b6b; border-radius: 50%; will-change: transform; }
  </style>
</head>
<body>
  <section id="hero">Hero Section</section>
  <section id="parallax">
    <div class="parallax-img" id="img"></div>
  </section>
  <script>
    gsap.registerPlugin(ScrollTrigger);
    gsap.to("#img", {
      scrollTrigger: {
        trigger: "#parallax",
        start: "top bottom",
        end: "bottom top",
        scrub: 1,
        markers: true
      },
      y: -200,
      rotation: 180,
      scale: 1.5,
      ease: "none"
    });
  </script>
</body>
</html>

ScrollTrigger enregistre le plugin, scrub:1 lie vitesse animation au scroll (1s délai). Markers debuguent bounds. Parfait pour parallax : img monte/rotate pendant scroll. Piège : 'anticipatePin:1' pour mobile lag ; rafraîchissez via ScrollTrigger.refresh() post-resize.

Pinning et batch reveal

demo-pin-batch.html
<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>GSAP Pin & Batch</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.5/gsap.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.5/ScrollTrigger.min.js"></script>
  <style>
    body { margin: 0; font-family: Arial; }
    .sticky { height: 200vh; position: relative; }
    .pin { position: sticky; top: 0; height: 100vh; background: #4ecdc4; display: flex; align-items: center; justify-content: center; font-size: 2em; }
    .card { opacity: 0; padding: 20px; margin: 20px; background: white; border-radius: 10px; box-shadow: 0 5px 15px rgba(0,0,0,0.1); }
  </style>
</head>
<body>
  <div class="sticky">
    <div class="pin">Section Pinée</div>
  </div>
  <div class="cards">
    <div class="card">Carte 1</div>
    <div class="card">Carte 2</div>
    <div class="card">Carte 3</div>
  </div>
  <script>
    gsap.registerPlugin(ScrollTrigger);
    ScrollTrigger.create({
      trigger: ".sticky",
      start: "top top",
      end: "bottom bottom",
      pin: ".pin",
      pinSpacing: false
    });
    ScrollTrigger.batch(".card", {
      onEnter: batch => gsap.to(batch, { opacity: 1, x: 0, stagger: 0.1 }),
      onLeave: batch => gsap.to(batch, { opacity: 0, x: -50 }),
      onEnterBack: batch => gsap.to(batch, { opacity: 1, x: 0 }),
      onLeaveBack: batch => gsap.to(batch, { opacity: 0, x: 50 }),
      start: "top 80%",
      end: "bottom 20%",
      markers: true
    });
  </script>
</body>
</html>

Pin fige .pin pendant scroll, batch anime groupes d'éléments via callbacks onEnter/onLeave bidirectionnels. Idéal pour reveals en grille sans timelines lourdes. Piège : pinSpacing: false évite espaces vides ; limitez à 10-20 éléments par batch pour perf.

Optimisations avancées avec utilities

Utilisez gsap.utils pour loops distribués (toArray, mapRange). gsap.context() scope animations pour cleanup React. MatchMedia adapte à breakpoints : ScrollTrigger.matchMedia({ '(min-width: 768px)': () => { / desktop / } }).

MorphSVG avec utils et context

demo-morphsvg.html
<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>GSAP MorphSVG</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.5/gsap.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.5/MorphSVGPlugin.min.js"></script>
  <style>
    body { margin: 0; height: 100vh; display: flex; align-items: center; justify-content: center; background: #222; }
    svg { width: 300px; height: 300px; }
  </style>
</head>
<body>
  <svg viewBox="0 0 200 200">
    <path id="shape1" d="M100,10 L40,198 L190,78 Z" fill="#4a90e2" stroke="#333" stroke-width="2"/>
    <path id="shape2" d="M10,100 Q50,10 100,100 T190,100" fill="none" stroke="#e94b3c" stroke-width="20" stroke-linecap="round" stroke-linejoin="round" opacity="0"/>
  </svg>
  <script>
    gsap.registerPlugin(MorphSVGPlugin);
    const ctx = gsap.context(() => {
      gsap.to("#shape1", {
        morphSVG: "#shape2",
        duration: 2,
        repeat: -1,
        yoyo: true,
        ease: "power2.inOut"
      });
    });
    // Cleanup: ctx.kill() in React useEffect return
  </script>
</body>
</html>

MorphSVGPlugin (bonus gratuit via GSAP account/CDN) interpole paths SVG pour transitions fluides triangle→arc. gsap.context() encapsule pour perf/cleanup. Piège : Paths doivent avoir même nombre points ; précisez type:"morph" si auto-detect échoue.

Bonnes pratiques

  • Toujours utiliser will-change: transform sur éléments animés pour layer GPU.
  • Rafraîchir ScrollTrigger après DOM changes : ScrollTrigger.refresh().
  • Batching avec gsap.ticker pour 100+ anims sans drop FPS.
  • Lazy-load GSAP via dynamic import en SPA.
  • Testez sur mobile : forcez 60Hz, throttle network.

Erreurs courantes à éviter

  • Ne pas kill() timelines : memory leaks sur single-page apps → utilisez gsap.context().
  • Oublier registerPlugin : ScrollTrigger/MorphSVG inertes sans appel.
  • Easings par défaut : 'power1.out' fade fade ; préférez 'back.out(1.7)' pour punch.
  • Animations non-reversible : sans yoyo/repeatBack, scroll up bugge.

Pour aller plus loin

Approfondissez avec la doc officielle GSAP. Intégrez à React via gsap-context. Découvrez nos formations Learni sur animations avancées pour projets live. Forum GSAP : mine d'exemples pros.

Comment maîtriser GSAP animations avancées 2026 | Learni