Développement GSAP & ScrollTrigger
Aperçu
GSAP (GreenSock Animation Platform) est la bibliothèque d'animation JavaScript de référence pour créer des animations de haute qualité et hautes performances. ScrollTrigger est le puissant plugin de GSAP pour les animations pilotées par le défilement. Ensemble, ils permettent tout, des simples transitions d'interface aux expériences narratives complexes basées sur le défilement.
Concepts fondamentaux
Les bases : les Tweens
Un tween est une animation unique d'un point A à un point B.
// Animer VERS un état (depuis l'état actuel)
gsap.to(".box", {
x: 200,
rotation: 360,
duration: 1,
ease: "power2.inOut"
});
// Animer DEPUIS un état (vers l'état actuel)
gsap.from(".box", {
opacity: 0,
y: -50,
duration: 0.8
});
// Animer DE-VERS (définir à la fois le début et la fin)
gsap.fromTo(".box",
{ opacity: 0, scale: 0.5 }, // DEPUIS
{ opacity: 1, scale: 1, duration: 1 } // VERS
);
Timelines : Séquencement d'animations
Les timelines orchestrent plusieurs tweens en séquence ou en chevauchement.
const tl = gsap.timeline();
// Séquentiel par défaut
tl.to(".box1", { x: 100, duration: 1 })
.to(".box2", { y: 100, duration: 1 })
.to(".box3", { rotation: 360, duration: 1 });
// Avec des labels pour l'organisation
tl.addLabel("start")
.to(".hero", { opacity: 1, duration: 1 })
.addLabel("reveal")
.to(".content", { y: 0, duration: 0.8 }, "reveal") // Commence au label "reveal"
.to(".cta", { scale: 1, duration: 0.5 }, "reveal+=0.5"); // 0.5s après "reveal"
Paramètre de position (Timing des timelines)
Contrôle le moment où les animations commencent dans une timeline :
const tl = gsap.timeline();
// Par défaut : L'une après l'autre
tl.to(".box1", { x: 100 })
.to(".box2", { x: 100 }); // Commence après la fin de box1
// Commencer en même temps
tl.to(".box1", { x: 100 })
.to(".box2", { y: 100 }, 0); // Commence à 0 seconde
// Positionnement relatif
tl.to(".box1", { x: 100, duration: 2 })
.to(".box2", { y: 100 }, "-=1"); // Commence 1 seconde avant la fin de box1
.to(".box3", { rotation: 360 }, "+=0.5"); // Commence 0.5s après la fin de box2
// À un moment précis
tl.to(".box1", { x: 100 }, 2.5); // Commence à 2.5 secondes
Principes fondamentaux de ScrollTrigger
Animation de défilement de base
gsap.registerPlugin(ScrollTrigger);
gsap.to(".box", {
x: 500,
scrollTrigger: {
trigger: ".box",
start: "top center", // Quand le haut du déclencheur atteint le centre de la fenêtre
end: "bottom center",
markers: true, // Développement uniquement - affiche les positions de début/fin
scrub: true, // Lie l'animation à la barre de défilement
toggleActions: "play none none reverse" // onEnter onLeave onEnterBack onLeaveBack
}
});
Positions de début et de fin
Format : "[position du déclencheur] [position de la fenêtre]"
// Schémas courants
start: "top top" // Le haut du déclencheur touche le haut de la fenêtre
start: "top center" // Le haut du déclencheur touche le centre de la fenêtre (par défaut)
start: "top bottom" // Le haut du déclencheur touche le bas de la fenêtre
start: "center center" // Le centre du déclencheur touche le centre de la fenêtre
// Avec décalages
start: "top top+=100" // 100px sous le haut de la fenêtre
start: "top 80%" // 80% en bas de la fenêtre
end: "+=500" // 500px après la position de début
end: "bottom top" // Le bas du déclencheur touche le haut de la fenêtre
Scrubbing (Animation synchronisée avec le défilement)
// Booléen : Lien direct avec la barre de défilement (immédiat)
scrub: true
// Nombre : Délai de lissage en secondes
scrub: 1 // Prend 1 seconde pour "rattraper" la barre de défilement
scrub: 0.5 // Plus rapide, sensation plus serrée
Actions de basculement (Toggle Actions)
Contrôle l'animation à quatre points de défilement :
toggleActions: "play pause resume reset"
// onEnter | onLeave | onEnterBack | onLeaveBack
// Actions : play, pause, resume, restart, reset, complete, reverse, none
Schémas courants :
toggleActions: "play none none none" // Jouer une fois à l'entrée
toggleActions: "play none none reverse" // Jouer en avant, inverser en arrière
toggleActions: "play complete reverse reset" // Contrôle total
toggleActions: "restart pause resume pause" // Redémarrer à chaque entrée
Schémas courants
1. Apparition en fondu au défilement
gsap.from(".fade-in", {
opacity: 0,
y: 50,
duration: 1,
scrollTrigger: {
trigger: ".fade-in",
start: "top 80%",
end: "top 50%",
scrub: 1,
once: true // Animer une seule fois
}
});
2. Épingler un élément pendant le défilement
ScrollTrigger.create({
trigger: ".panel",
start: "top top",
end: "+=500", // Épingler pendant 500px de défilement
pin: true,
pinSpacing: true // Ajouter un espacement (vrai par défaut)
});
3. Section de défilement horizontal
const sections = gsap.utils.toArray(".panel");
gsap.to(sections, {
xPercent: -100 * (sections.length - 1),
ease: "none",
scrollTrigger: {
trigger: ".container",
pin: true,
scrub: 1,
end: () => "+=" + document.querySelector(".container").offsetWidth
}
});
4. Effet de parallaxe
// Mouvement plus lent (couche d'arrière-plan)
gsap.to(".bg", {
y: 200,
ease: "none",
scrollTrigger: {
trigger: ".section",
start: "top bottom",
end: "bottom top",
scrub: true
}
});
// Mouvement plus rapide (couche de premier plan)
gsap.to(".fg", {
y: -100,
ease: "none",
scrollTrigger: {
trigger: ".section",
start: "top bottom",
end: "bottom top",
scrub: true
}
});
5. Timeline déclenchée par le défilement
const tl = gsap.timeline({
scrollTrigger: {
trigger: ".container",
start: "top top",
end: "+=500",
scrub: 1,
pin: true,
snap: {
snapTo: "labels", // S'accrocher aux labels de la timeline
duration: { min: 0.2, max: 3 },
delay: 0.2,
ease: "power1.inOut"
}
}
});
tl.addLabel("start")
.from(".title", { scale: 0.3, rotation: 45, autoAlpha: 0 })
.addLabel("color")
.from(".box", { backgroundColor: "#28a92b" })
.addLabel("spin")
.to(".box", { rotation: 360 })
.addLabel("end");
6. Animations par lots (plusieurs éléments)
// Boucle sur plusieurs éléments
gsap.utils.toArray(".box").forEach((box, i) => {
gsap.from(box, {
y: 100,
opacity: 0,
scrollTrigger: {
trigger: box,
start: "top 80%",
end: "top 50%",
scrub: 1
}
});
});
// Ou utiliser ScrollTrigger.batch
ScrollTrigger.batch(".box", {
onEnter: batch => gsap.to(batch, { opacity: 1, y: 0, stagger: 0.15 }),
onLeave: batch => gsap.set(batch, { opacity: 0 }),
start: "top 80%",
once: true
});
7. Animations décalées (Staggered)
gsap.from(".item", {
y: 50,
opacity: 0,
duration: 0.8,
stagger: 0.1, // 0.1s entre chaque élément
scrollTrigger: {
trigger: ".grid",
start: "top 80%"
}
});
// Décalage avancé
gsap.from(".item", {
scale: 0,
duration: 1,
stagger: {
each: 0.1,
from: "center", // "start", "center", "end", "edges", ou numéro d'index
grid: "auto", // Pour les grilles
ease: "power2.inOut"
}
});
Schémas d'intégration
Avec Three.js / WebGL
import * as THREE from 'three';
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
gsap.registerPlugin(ScrollTrigger);
// Animer la caméra
gsap.to(camera.position, {
x: 5,
y: 3,
z: 10,
scrollTrigger: {
trigger: "#section2",
start: "top top",
end: "bottom top",
scrub: 1,
onUpdate: () => camera.lookAt(scene.position)
}
});
// Animer la rotation d'un maillage
gsap.to(mesh.rotation, {
y: Math.PI * 2,
scrollTrigger: {
trigger: "#section3",
start: "top bottom",
end: "bottom top",
scrub: true
}
});
// Animer les propriétés du matériau
gsap.to(material, {
opacity: 0,
scrollTrigger: {
trigger: "#section4",
start: "top center",
end: "center center",
scrub: 1
}
});
Avec React (Hook useGSAP)
import { useRef } from 'react';
import { useGSAP } from '@gsap/react';
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
gsap.registerPlugin(ScrollTrigger);
function Component() {
const container = useRef();
const box = useRef();
useGSAP(() => {
gsap.to(box.current, {
x: 200,
scrollTrigger: {
trigger: box.current,
start: "top center",
end: "bottom center",
scrub: true,
markers: true
}
});
}, { scope: container }); // Portée pour le nettoyage
return (
<div ref={container}>
<div ref={box} className="box">Boîte animée</div>
</div>
);
}
Partager une timeline dans React
function App() {
const [tl, setTl] = useState();
useGSAP(() => {
const timeline = gsap.timeline();
setTl(timeline);
}, []);
return (
<div>
<Box timeline={tl} index={0} />
<Circle timeline={tl} index={1} />
</div>
);
}
function Box({ timeline, index }) {
const ref = useRef();
useGSAP(() => {
timeline && timeline.to(ref.current, { x: 100 }, index * 0.1);
}, [timeline, index]);
return <div ref={ref} className="box" />;
}
Intégration Locomotive Scroll
import LocomotiveScroll from 'locomotive-scroll';
const scroller = new LocomotiveScroll({
el: document.querySelector('[data-scroll-container]'),
smooth: true
});
ScrollTrigger.scrollerProxy("[data-scroll-container]", {
scrollTop(value) {
return arguments.length ? scroller.scrollTo(value, 0, 0) : scroller.scroll.instance.scroll.y;
},
getBoundingClientRect() {
return {top: 0, left: 0, width: window.innerWidth, height: window.innerHeight};
},
pinType: document.querySelector("[data-scroll-container]").style.transform ? "transform" : "fixed"
});
ScrollTrigger.addEventListener("refresh", () => scroller.update());
ScrollTrigger.refresh();
Techniques avancées
Séquence d'images avec scrubbing
const canvas = document.querySelector("canvas");
const context = canvas.getContext("2d");
const images = [];
const imageCount = 147;
const currentFrame = { value: 0 };
for (let i = 0; i < imageCount; i++) {
const img = new Image();
img.src = `./frames/frame_${i.toString().padStart(4, '0')}.jpg`;
images.push(img);
}
images[0].onload = () => {
canvas.width = images[0].width;
canvas.height = images[0].height;
render();
};
function render() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.drawImage(images[Math.floor(currentFrame.value)], 0, 0);
}
gsap.to(currentFrame, {
value: imageCount - 1,
snap: "value",
ease: "none",
scrollTrigger: {
trigger: canvas,
start: "top top",
end: "+=500%",
scrub: true,
pin: true
},
onUpdate: render
});
Défilement fluide vers un élément
gsap.registerPlugin(ScrollToPlugin);
// Défiler vers un élément
gsap.to(window, {
duration: 1,
scrollTo: "#section2",
ease: "power2.inOut"
});
// Avec décalage
gsap.to(window, {
duration: 1.5,
scrollTo: { y: "#section2", offsetY: 50 },
ease: "expo.inOut"
});
// Défilement horizontal
gsap.to(".container", {
duration: 2,
scrollTo: { x: 1000, autoKill: true }
});
Animations conditionnelles (Media Queries)
ScrollTrigger.matchMedia({
// Desktop
"(min-width: 800px)": function() {
gsap.to(".box", {
x: 500,
scrollTrigger: {
trigger: ".box",
start: "top center",
end: "bottom top",
scrub: true
}
});
},
// Mobile
"(max-width: 799px)": function() {
gsap.to(".box", {
y: 200,
scrollTrigger: {
trigger: ".box",
start: "top 80%",
scrub: 1
}
});
}
});
Meilleures pratiques en matière de performance
1. Utiliser will-change en CSS
.animated-element {
will-change: transform, opacity;
}
2. Limiter les repaints
// Bien : Animer transform/opacity (accéléré GPU)
gsap.to(".box", { x: 100, opacity: 0.5 });
// Éviter : Animer les propriétés de mise en page
// gsap.to(".box", { width: 500, height: 300 }); // Provoque un reflow
3. Supprimer les ScrollTriggers
// Tuer un déclencheur individuel
const trigger = ScrollTrigger.create({ /* ... */ });
trigger.kill();
// Tuer tous les déclencheurs
ScrollTrigger.getAll().forEach(t => t.kill());
// Dans React avec nettoyage
useGSAP(() => {
const tween = gsap.to(".box", { /* ... */ });
return () => {
tween.kill();
};
}, []);
4. Debounce le redimensionnement
ScrollTrigger gère cela automatiquement, mais pour une logique de redimensionnement personnalisée :
let resizeTimer;
window.addEventListener("resize", () => {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(() => {
ScrollTrigger.refresh();
}, 250);
});
5. Utiliser invalidateOnRefresh
Pour les valeurs dynamiques qui changent lors du redimensionnement :
gsap.to(".box", {
x: () => window.innerWidth / 2, // Valeur dynamique
scrollTrigger: {
trigger: ".box",
start: "top center",
invalidateOnRefresh: true // Recalculer x lors du redimensionnement
}
});
Pièges courants
1. Plusieurs tweens sur le même élément
// Problème : Le deuxième tween entre en conflit avec le premier
gsap.to('h1', { x: 100, scrollTrigger: { /* ... */ } });
gsap.to('h1', { x: 200, scrollTrigger: { /* ... */ } }); // Saute !
// Solution 1 : Utiliser fromTo
gsap.fromTo('h1', { x: 100 }, { x: 200, scrollTrigger: { /* ... */ } });
// Solution 2 : Utiliser immediateRender: false
gsap.to('h1', { x: 200, immediateRender: false, scrollTrigger: { /* ... */ } });
// Solution 3 : Appliquer ScrollTrigger à une timeline
const tl = gsap.timeline({ scrollTrigger: { /* ... */ } });
tl.to('h1', { x: 100 })
.to('h1', { x: 200 });
2. Ne pas utiliser de boucles pour plusieurs éléments
// Faux : Anime tous en même temps
gsap.to('.section', {
y: -100,
scrollTrigger: { trigger: '.section', scrub: true }
});
// Correct : Boucle pour des déclencheurs individuels
gsap.utils.toArray('.section').forEach(section => {
gsap.to(section, {
y: -100,
scrollTrigger: { trigger: section, scrub: true }
});
});
3. Oublier d'enregistrer les plugins
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
import { ScrollToPlugin } from 'gsap/ScrollToPlugin';
gsap.registerPlugin(ScrollTrigger, ScrollToPlugin);
4. Mauvaise gestion du z-index avec l'épinglage
// Si plusieurs sections sont épinglées, utilisez zIndex
ScrollTrigger.create({
trigger: ".panel-1",
start: "top top",
end: "bottom top",
pin: true,
pinSpacing: false
});
ScrollTrigger.create({
trigger: ".panel-2",
start: "top top",
end: "bottom top",
pin: true,
pinSpacing: false
});
/* CSS */
.panel-1 { z-index: 2; position: relative; }
.panel-2 { z-index: 1; position: relative; }