Desarrollo con GSAP y ScrollTrigger
Descripción general
GSAP (GreenSock Animation Platform) es la biblioteca de animación JavaScript líder en la industria para crear animaciones de alto rendimiento y calidad de producción. ScrollTrigger es el potente plugin de GSAP para animaciones basadas en desplazamiento. Juntos, permiten desde transiciones simples de interfaz de usuario hasta complejas experiencias narrativas basadas en desplazamiento.
Conceptos fundamentales
Conceptos básicos: Interpolaciones (Tweens)
Una interpolación (tween) es una animación única del punto A al punto B.
// Animar HACIA un estado (desde el actual)
gsap.to(".box", {
x: 200,
rotation: 360,
duration: 1,
ease: "power2.inOut"
});
// Animar DESDE un estado (hacia el actual)
gsap.from(".box", {
opacity: 0,
y: -50,
duration: 0.8
});
// Animar DESDE-HACIA (definir tanto inicio como fin)
gsap.fromTo(".box",
{ opacity: 0, scale: 0.5 }, // DESDE
{ opacity: 1, scale: 1, duration: 1 } // HACIA
);
Líneas de tiempo: Secuenciación de animaciones
Las líneas de tiempo orquestan múltiples interpolaciones en secuencia o superposición.
const tl = gsap.timeline();
// Por defecto, secuenciales
tl.to(".box1", { x: 100, duration: 1 })
.to(".box2", { y: 100, duration: 1 })
.to(".box3", { rotation: 360, duration: 1 });
// Con etiquetas para organización
tl.addLabel("start")
.to(".hero", { opacity: 1, duration: 1 })
.addLabel("reveal")
.to(".content", { y: 0, duration: 0.8 }, "reveal") // Comienza en la etiqueta "reveal"
.to(".cta", { scale: 1, duration: 0.5 }, "reveal+=0.5"); // 0.5s después de "reveal"
Parámetro de posición (Tiempo en la línea de tiempo)
Controla cuándo comienzan las animaciones dentro de una línea de tiempo:
const tl = gsap.timeline();
// Por defecto: Una después de otra
tl.to(".box1", { x: 100 })
.to(".box2", { x: 100 }); // Comienza después de que box1 termina
// Comienzan al mismo tiempo
tl.to(".box1", { x: 100 })
.to(".box2", { y: 100 }, 0); // Comienza en el segundo 0
// Posicionamiento relativo
tl.to(".box1", { x: 100, duration: 2 })
.to(".box2", { y: 100 }, "-=1"); // Comienza 1 segundo antes de que box1 termine
.to(".box3", { rotation: 360 }, "+=0.5"); // Comienza 0.5s después de que box2 termine
// En un momento específico
tl.to(".box1", { x: 100 }, 2.5); // Comienza en el segundo 2.5
Fundamentos de ScrollTrigger
Animación básica con desplazamiento
gsap.registerPlugin(ScrollTrigger);
gsap.to(".box", {
x: 500,
scrollTrigger: {
trigger: ".box",
start: "top center", // Cuando la parte superior del disparador llega al centro de la ventana
end: "bottom center",
markers: true, // Solo durante el desarrollo: muestra las posiciones de inicio y fin
scrub: true, // Vincula la animación a la barra de desplazamiento
toggleActions: "play none none reverse" // onEnter onLeave onEnterBack onLeaveBack
}
});
Posiciones de inicio y fin
Formato: "[posición del disparador] [posición de la ventana]"
// Patrones comunes
start: "top top" // Parte superior del disparador toca la parte superior de la ventana
start: "top center" // Parte superior del disparador toca el centro de la ventana (por defecto)
start: "top bottom" // Parte superior del disparador toca la parte inferior de la ventana
start: "center center" // Centro del disparador toca el centro de la ventana
// Con desplazamientos
start: "top top+=100" // 100px por debajo de la parte superior de la ventana
start: "top 80%" // 80% hacia abajo de la ventana
end: "+=500" // 500px después de la posición de inicio
end: "bottom top" // Parte inferior del disparador toca la parte superior de la ventana
Sincronización (Scrubbing) con el desplazamiento
// Booleano: Enlace directo a la barra de desplazamiento (inmediato)
scrub: true
// Número: Retardo de suavizado en segundos
scrub: 1 // Tarda 1 segundo en "alcanzar" a la barra de desplazamiento
scrub: 0.5 // Más rápido, sensación más ajustada
Acciones de alternancia (Toggle Actions)
Controla la animación en cuatro puntos de desplazamiento:
toggleActions: "play pause resume reset"
// onEnter | onLeave | onEnterBack | onLeaveBack
// Acciones: play, pause, resume, restart, reset, complete, reverse, none
Patrones comunes:
toggleActions: "play none none none" // Reproducir una vez al entrar
toggleActions: "play none none reverse" // Reproducir hacia adelante, invertir al retroceder
toggleActions: "play complete reverse reset" // Control total
toggleActions: "restart pause resume pause" // Reiniciar en cada entrada
Patrones comunes
1. Aparición gradual al desplazarse
gsap.from(".fade-in", {
opacity: 0,
y: 50,
duration: 1,
scrollTrigger: {
trigger: ".fade-in",
start: "top 80%",
end: "top 50%",
scrub: 1,
once: true // Animación única
}
});
2. Fijar elemento mientras se desplaza
ScrollTrigger.create({
trigger: ".panel",
start: "top top",
end: "+=500", // Fijar durante 500px de desplazamiento
pin: true,
pinSpacing: true // Agregar espacio (por defecto true)
});
3. Sección de desplazamiento 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. Efecto de paralaje
// Movimiento más lento (capa de fondo)
gsap.to(".bg", {
y: 200,
ease: "none",
scrollTrigger: {
trigger: ".section",
start: "top bottom",
end: "bottom top",
scrub: true
}
});
// Movimiento más rápido (capa de primer plano)
gsap.to(".fg", {
y: -100,
ease: "none",
scrollTrigger: {
trigger: ".section",
start: "top bottom",
end: "bottom top",
scrub: true
}
});
5. Línea de tiempo activada por desplazamiento
const tl = gsap.timeline({
scrollTrigger: {
trigger: ".container",
start: "top top",
end: "+=500",
scrub: 1,
pin: true,
snap: {
snapTo: "labels", // Ajustar a etiquetas de la línea de tiempo
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. Animaciones en lote (Múltiples elementos)
// Recorrer múltiples elementos
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
}
});
});
// O usar 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. Animaciones escalonadas
gsap.from(".item", {
y: 50,
opacity: 0,
duration: 0.8,
stagger: 0.1, // 0.1s entre cada elemento
scrollTrigger: {
trigger: ".grid",
start: "top 80%"
}
});
// Escalonamiento avanzado
gsap.from(".item", {
scale: 0,
duration: 1,
stagger: {
each: 0.1,
from: "center", // "start", "center", "end", "edges" o número de índice
grid: "auto", // Para diseños de cuadrícula
ease: "power2.inOut"
}
});
Patrones de integración
Con Three.js / WebGL
import * as THREE from 'three';
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
gsap.registerPlugin(ScrollTrigger);
// Animar cámara
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)
}
});
// Animar rotación de malla
gsap.to(mesh.rotation, {
y: Math.PI * 2,
scrollTrigger: {
trigger: "#section3",
start: "top bottom",
end: "bottom top",
scrub: true
}
});
// Animar propiedades del material
gsap.to(material, {
opacity: 0,
scrollTrigger: {
trigger: "#section4",
start: "top center",
end: "center center",
scrub: 1
}
});
Con 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 }); // Delimitación para limpieza
return (
<div ref={container}>
<div ref={box} className="box">Caja Animada</div>
</div>
);
}
Compartir línea de tiempo en 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" />;
}
Integración con 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();
Técnicas avanzadas
Sincronización de secuencia de imágenes
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
});
Desplazamiento suave a un elemento
gsap.registerPlugin(ScrollToPlugin);
// Desplazar a un elemento
gsap.to(window, {
duration: 1,
scrollTo: "#section2",
ease: "power2.inOut"
});
// Con desplazamiento
gsap.to(window, {
duration: 1.5,
scrollTo: { y: "#section2", offsetY: 50 },
ease: "expo.inOut"
});
// Desplazamiento horizontal
gsap.to(".container", {
duration: 2,
scrollTo: { x: 1000, autoKill: true }
});
Animaciones condicionales (Consultas de medios)
ScrollTrigger.matchMedia({
// Escritorio
"(min-width: 800px)": function() {
gsap.to(".box", {
x: 500,
scrollTrigger: {
trigger: ".box",
start: "top center",
end: "bottom top",
scrub: true
}
});
},
// Móvil
"(max-width: 799px)": function() {
gsap.to(".box", {
y: 200,
scrollTrigger: {
trigger: ".box",
start: "top 80%",
scrub: 1
}
});
}
});
Mejores prácticas de rendimiento
1. Usar CSS will-change
.animated-element {
will-change: transform, opacity;
}
2. Limitar repintados
// Bueno: Animar transform/opacity (acelerado por GPU)
gsap.to(".box", { x: 100, opacity: 0.5 });
// Evitar: Animar propiedades de diseño
// gsap.to(".box", { width: 500, height: 300 }); // Provoca reflujo (reflow)
3. Eliminar ScrollTriggers
// Eliminar un disparador individual
const trigger = ScrollTrigger.create({ /* ... */ });
trigger.kill();
// Eliminar todos los disparadores
ScrollTrigger.getAll().forEach(t => t.kill());
// En React con limpieza
useGSAP(() => {
const tween = gsap.to(".box", { /* ... */ });
return () => {
tween.kill();
};
}, []);
4. Antirrebote en cambio de tamaño
ScrollTrigger maneja esto automáticamente, pero para lógica de cambio de tamaño personalizada:
let resizeTimer;
window.addEventListener("resize", () => {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(() => {
ScrollTrigger.refresh();
}, 250);
});
5. Usar invalidateOnRefresh
Para valores dinámicos que cambian al redimensionar:
gsap.to(".box", {
x: () => window.innerWidth / 2, // Valor dinámico
scrollTrigger: {
trigger: ".box",
start: "top center",
invalidateOnRefresh: true // Recalcular x al redimensionar
}
});
Errores comunes
1. Múltiples interpolaciones en el mismo elemento
// Problema: La segunda interpolación entra en conflicto con la primera
gsap.to('h1', { x: 100, scrollTrigger: { /* ... */ } });
gsap.to('h1', { x: 200, scrollTrigger: { /* ... */ } }); // ¡Salta!
// Solución 1: Usar fromTo
gsap.fromTo('h1', { x: 100 }, { x: 200, scrollTrigger: { /* ... */ } });
// Solución 2: Usar immediateRender: false
gsap.to('h1', { x: 200, immediateRender: false, scrollTrigger: { /* ... */ } });
// Solución 3: Aplicar ScrollTrigger a la línea de tiempo
const tl = gsap.timeline({ scrollTrigger: { /* ... */ } });
tl.to('h1', { x: 100 })
.to('h1', { x: 200 });
2. No usar bucles para múltiples elementos
// Incorrecto: Anima todos a la vez
gsap.to('.section', {
y: -100,
scrollTrigger: { trigger: '.section', scrub: true }
});
// Correcto: Bucle para disparadores individuales
gsap.utils.toArray('.section').forEach(section => {
gsap.to(section, {
y: -100,
scrollTrigger: { trigger: section, scrub: true }
});
});
3. Olvidar registrar plugins
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
import { ScrollToPlugin } from 'gsap/ScrollToPlugin';
gsap.registerPlugin(ScrollTrigger, ScrollToPlugin); // ¡Siempre registrar!
4. Ignorar el estado inicial de los elementos
// Problema: La animación comienza desde el estado visible actual
gsap.to(".box", { opacity: 0 }); // Solo si el elemento es visible inicialmente
// Solución: Usar set para definir estado inicial
gsap.set(".box", { opacity: 0 });
gsap.to(".box", { opacity: 1, scrollTrigger: { trigger: ".box", start: "top 80%" } });
5. No manejar el desmontaje en React
// Incorrecto: La limpieza no se implementa
function Component() {
useGSAP(() => {
gsap.to(".box", { x: 100 });
});
}
// Correcto: La limpieza se maneja automáticamente con useGSAP
function Component() {
useGSAP(() => {
gsap.to(".box", { x: 100 });
}, []); // Se limpia automáticamente al desmontar
}
Recursos
- Documentación oficial de GSAP
- Documentación de ScrollTrigger
- GSAP en CodePen - Colección de ejemplos oficiales
- Tutoriales GSAP - Guías y tutoriales oficiales
- GSAP en GitHub - Código fuente y problemas