Desenvolvimento com GSAP e ScrollTrigger
Visão Geral
O GSAP (GreenSock Animation Platform) é a principal biblioteca de animação JavaScript do setor para criar animações de alta performance e qualidade profissional. O ScrollTrigger é o poderoso plugin do GSAP para animações baseadas em rolagem. Juntos, eles permitem desde transições simples de UI até experiências complexas de storytelling baseadas em rolagem.
Conceitos Principais
O Básico: Tweens
Um tween é uma animação única do ponto A ao ponto B.
// Animar PARA um estado (a partir do atual)
gsap.to(".box", {
x: 200,
rotation: 360,
duration: 1,
ease: "power2.inOut"
});
// Animar DE um estado (para o atual)
gsap.from(".box", {
opacity: 0,
y: -50,
duration: 0.8
});
// Animar DE-PARA (definir início e fim)
gsap.fromTo(".box",
{ opacity: 0, scale: 0.5 }, // DE
{ opacity: 1, scale: 1, duration: 1 } // PARA
);
Timelines: Sequenciando Animações
Timelines orquestram múltiplos tweens em sequência ou sobreposição.
const tl = gsap.timeline();
// Sequencial por padrão
tl.to(".box1", { x: 100, duration: 1 })
.to(".box2", { y: 100, duration: 1 })
.to(".box3", { rotation: 360, duration: 1 });
// Com labels para organização
tl.addLabel("start")
.to(".hero", { opacity: 1, duration: 1 })
.addLabel("reveal")
.to(".content", { y: 0, duration: 0.8 }, "reveal") // Inicia no label "reveal"
.to(".cta", { scale: 1, duration: 0.5 }, "reveal+=0.5"); // 0,5s após "reveal"
Parâmetro de Posição (Tempo na Timeline)
Controle quando as animações começam dentro de uma timeline:
const tl = gsap.timeline();
// Padrão: Uma após a outra
tl.to(".box1", { x: 100 })
.to(".box2", { x: 100 }); // Inicia após box1 terminar
// Iniciar ao mesmo tempo
tl.to(".box1", { x: 100 })
.to(".box2", { y: 100 }, 0); // Inicia em 0 segundos
// Posicionamento relativo
tl.to(".box1", { x: 100, duration: 2 })
.to(".box2", { y: 100 }, "-=1"); // Inicia 1 segundo antes de box1 terminar
.to(".box3", { rotation: 360 }, "+=0.5"); // Inicia 0,5s após box2 terminar
// Em um tempo específico
tl.to(".box1", { x: 100 }, 2.5); // Inicia em 2,5 segundos
Fundamentos do ScrollTrigger
Animação Básica com Scroll
gsap.registerPlugin(ScrollTrigger);
gsap.to(".box", {
x: 500,
scrollTrigger: {
trigger: ".box",
start: "top center", // Quando o topo do trigger atinge o centro da viewport
end: "bottom center",
markers: true, // Apenas desenvolvimento - mostra posições start/end
scrub: true, // Liga a animação à barra de rolagem
toggleActions: "play none none reverse" // onEnter onLeave onEnterBack onLeaveBack
}
});
Posições Start e End
Formato: "[posição do trigger] [posição da viewport]"
// Padrões comuns
start: "top top" // Topo do trigger atinge o topo da viewport
start: "top center" // Topo do trigger atinge o centro da viewport (padrão)
start: "top bottom" // Topo do trigger atinge a parte inferior da viewport
start: "center center" // Centro do trigger atinge o centro da viewport
// Com deslocamentos
start: "top top+=100" // 100px abaixo do topo da viewport
start: "top 80%" // 80% abaixo da viewport
end: "+=500" // 500px após a posição inicial
end: "bottom top" // Parte inferior do trigger atinge o topo da viewport
Scrubbing (Animação Sincronizada com Scroll)
// Booleano: Link direto à barra de rolagem (imediato)
scrub: true
// Número: Atraso de suavização em segundos
scrub: 1 // Leva 1 segundo para "alcançar" a barra de rolagem
scrub: 0.5 // Mais rápido, sensação mais justa
Ações de Alternância (Toggle Actions)
Controle a animação em quatro pontos de rolagem:
toggleActions: "play pause resume reset"
// onEnter | onLeave | onEnterBack | onLeaveBack
// Ações: play, pause, resume, restart, reset, complete, reverse, none
Padrões comuns:
toggleActions: "play none none none" // Tocar uma vez ao entrar
toggleActions: "play none none reverse" // Tocar para frente, reverter ao voltar
toggleActions: "play complete reverse reset" // Controle total
toggleActions: "restart pause resume pause" // Reiniciar a cada entrada
Padrões Comuns
1. Fade In ao Rolar
gsap.from(".fade-in", {
opacity: 0,
y: 50,
duration: 1,
scrollTrigger: {
trigger: ".fade-in",
start: "top 80%",
end: "top 50%",
scrub: 1,
once: true // Animar apenas uma vez
}
});
2. Fixar Elemento Durante a Rolagem
ScrollTrigger.create({
trigger: ".panel",
start: "top top",
end: "+=500", // Fixar por 500px de rolagem
pin: true,
pinSpacing: true // Adicionar espaçamento (padrão true)
});
3. Seção de Rolagem 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. Efeito Parallax
// Movimento mais lento (camada de fundo)
gsap.to(".bg", {
y: 200,
ease: "none",
scrollTrigger: {
trigger: ".section",
start: "top bottom",
end: "bottom top",
scrub: true
}
});
// Movimento mais rápido (camada de primeiro plano)
gsap.to(".fg", {
y: -100,
ease: "none",
scrollTrigger: {
trigger: ".section",
start: "top bottom",
end: "bottom top",
scrub: true
}
});
5. Timeline Acionada por Scroll
const tl = gsap.timeline({
scrollTrigger: {
trigger: ".container",
start: "top top",
end: "+=500",
scrub: 1,
pin: true,
snap: {
snapTo: "labels", // Ajustar aos labels da 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. Animações em Lote (Múltiplos Elementos)
// Percorrer vários 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
}
});
});
// Ou 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. Animações Escalonadas (Stagger)
gsap.from(".item", {
y: 50,
opacity: 0,
duration: 0.8,
stagger: 0.1, // 0,1s entre cada item
scrollTrigger: {
trigger: ".grid",
start: "top 80%"
}
});
// Escalonamento avançado
gsap.from(".item", {
scale: 0,
duration: 1,
stagger: {
each: 0.1,
from: "center", // "start", "center", "end", "edges" ou número de índice
grid: "auto", // Para layouts de grade
ease: "power2.inOut"
}
});
Padrões de Integração
Com Three.js / WebGL
import * as THREE from 'three';
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
gsap.registerPlugin(ScrollTrigger);
// Animar câmera
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 rotação da malha
gsap.to(mesh.rotation, {
y: Math.PI * 2,
scrollTrigger: {
trigger: "#section3",
start: "top bottom",
end: "bottom top",
scrub: true
}
});
// Animar propriedades do material
gsap.to(material, {
opacity: 0,
scrollTrigger: {
trigger: "#section4",
start: "top center",
end: "center center",
scrub: 1
}
});
Com 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 }); // Escopo para limpeza
return (
<div ref={container}>
<div ref={box} className="box">Box Animada</div>
</div>
);
}
Compartilhando Timeline no 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" />;
}
Integração com 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 Avançadas
Sequência de Imagens com Scrub
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
});
Rolagem Suave para Elemento
gsap.registerPlugin(ScrollToPlugin);
// Rolar para elemento
gsap.to(window, {
duration: 1,
scrollTo: "#section2",
ease: "power2.inOut"
});
// Com deslocamento
gsap.to(window, {
duration: 1.5,
scrollTo: { y: "#section2", offsetY: 50 },
ease: "expo.inOut"
});
// Rolagem horizontal
gsap.to(".container", {
duration: 2,
scrollTo: { x: 1000, autoKill: true }
});
Animações Condicionais (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
}
});
}
});
Melhores Práticas de Desempenho
1. Usar will-change CSS
.animated-element {
will-change: transform, opacity;
}
2. Limitar Repaints
// Bom: Animar transform/opacity (acelerado por GPU)
gsap.to(".box", { x: 100, opacity: 0.5 });
// Evitar: Animar propriedades de layout
// gsap.to(".box", { width: 500, height: 300 }); // Causa reflow
3. Descartar ScrollTriggers
// Matar trigger individual
const trigger = ScrollTrigger.create({ /* ... */ });
trigger.kill();
// Matar todos os triggers
ScrollTrigger.getAll().forEach(t => t.kill());
// No React com limpeza
useGSAP(() => {
const tween = gsap.to(".box", { /* ... */ });
return () => {
tween.kill();
};
}, []);
4. Debounce em Redimensionamento
ScrollTrigger lida com isso automaticamente, mas para lógica de redimensionamento personalizada:
let resizeTimer;
window.addEventListener("resize", () => {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(() => {
ScrollTrigger.refresh();
}, 250);
});
5. Usar invalidateOnRefresh
Para valores dinâmicos que mudam ao redimensionar:
gsap.to(".box", {
x: () => window.innerWidth / 2, // Valor dinâmico
scrollTrigger: {
trigger: ".box",
start: "top center",
invalidateOnRefresh: true // Recalcular x ao redimensionar
}
});
Armadilhas Comuns
1. Múltiplos Tweens no Mesmo Elemento
// Problema: Segundo tween conflita com o primeiro
gsap.to('h1', { x: 100, scrollTrigger: { /* ... */ } });
gsap.to('h1', { x: 200, scrollTrigger: { /* ... */ } }); // Salta!
// Solução 1: Usar fromTo
gsap.fromTo('h1', { x: 100 }, { x: 200, scrollTrigger: { /* ... */ } });
// Solução 2: Usar immediateRender: false
gsap.to('h1', { x: 200, immediateRender: false, scrollTrigger: { /* ... */ } });
// Solução 3: Aplicar ScrollTrigger à timeline
const tl = gsap.timeline({ scrollTrigger: { /* ... */ } });
tl.to('h1', { x: 100 })
.to('h1', { x: 200 });
2. Não Usar Loops para Múltiplos Elementos
// Errado: Anima todos de uma vez
gsap.to('.section', {
y: -100,
scrollTrigger: { trigger: '.section', scrub: true }
});
// Certo: Loop para triggers individuais
gsap.utils.toArray('.section').forEach(section => {
gsap.to(section, {
y: -100,
scrollTrigger: { trigger: section, scrub: true }
});
});
3. Esquecer de Registrar Plugins
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
import { ScrollToPlugin } from 'gsap/ScrollToPlugin';
gsap.registerPlugin(ScrollTrigger, ScrollToPlugin); // Necessário!
4. Ignorar Limpeza em SPA
// Exemplo com React
useEffect(() => {
const ctx = gsap.context(() => {
// Seus tweens/triggers aqui
gsap.to(".box", { x: 100, scrollTrigger: { /* ... */ } });
}, componentRef);
return () => ctx.revert(); // Limpa todos os registros GSAP
}, []);
Referência da API
Métodos do Tween
| Método | Descrição |
|---|---|
gsap.to() | Animar DE o estado atual PARA um novo |
gsap.from() | Animar DE um estado PARA o estado atual |
gsap.fromTo() | Animar DE um estado PARA outro |
gsap.set() | Definir propriedades sem animação |
Propriedades do Tween
{
duration: 1, // Duração em segundos
delay: 0, // Atraso antes de iniciar
ease: "power1.out", // Função de easing
repeat: 0, // Número de repetições (-1 para infinito)
yoyo: false, // Reverter a cada repetição
stagger: 0, // Atraso entre animações de lote
onComplete: () => {}, // Callback ao finalizar
}
Opções do ScrollTrigger
| Opção | Tipo | Descrição |
|---|---|---|
trigger | Element | Elemento que aciona a animação |
start | String | Posição inicial (ex: "top center") |
end | String | Posição final (ex: "bottom top") |
scrub | Boolean/Number | Liga ao scroll (true ou atraso em segundos) |
pin | Boolean/Element | Fixa o elemento durante a rolagem |
markers | Boolean | Mostrar marcadores de desenvolvimento |
toggleActions | String | Ações ao entrar/sair |
once | Boolean | Executar apenas uma vez |
snap | Object | Ajustar a posições na timeline |
onEnter | Function | Callback ao entrar no trigger |
onLeave | Function | Callback ao sair do trigger |
onUpdate | Function | Callback a cada atualização |
Valores de Easing
// Power (1-4): Controla a intensidade
ease: "power1.out" // Suave
ease: "power4.in" // Forte (aceleração abrupta)
// Padrões comuns
ease: "none" // Linear
ease: "back.out" // Leve extrapolação
ease: "elastic.out" // Efeito elástico
ease: "bounce.out" // Efeito de quique
ease: "steps(10)" // Animação em etapas discretas
// Combinações: in, out, inOut
ease: "power2.inOut" // Suaviza entrada e saída
Referência Rápida
Padrões de Inicialização
// HTML simples
gsap.registerPlugin(ScrollTrigger);
// NPM/Yarn
gsap.registerPlugin(ScrollTrigger);
// CDN
gsap.registerPlugin(ScrollTrigger);
Atalhos de Importação
// Importação completa
gsap.fromTo();
// Métodos de utilidade
gsap.utils.toArray();
gsap.utils.snap();
gsap.utils.random();
gsap.utils.distribute();
// Timelines
gsap.timeline();
Propriedades GSAP vs CSS
| GSAP | CSS | Acelerado por GPU |
|---|---|---|
x, y | transform | Sim |
rotation | transform | Sim |
scaleX, scaleY | transform | Sim |
opacity | opacity | Sim |
width, height | width, height | Não (causa reflow) |
color | color | Não |
Trechos de Código Rápidos
Fade In com Rolagem:
gsap.registerPlugin(ScrollTrigger);
gsap.from(".elemento", {
opacity: 0,
y: 50,
scrollTrigger: {
trigger: ".elemento",
start: "top 80%"
}
});
Seção Fixa:
ScrollTrigger.create({
trigger: ".painel",
start: "top top",
end: "+=300",
pin: true
});
Timeline com Scroll:
const tl = gsap.timeline({
scrollTrigger: {
trigger: ".container",
start: "top top",
end: "+=500",
scrub: 1,
pin: true
}
});
tl.to(".el1", { x: 100 }).to(".el2", { y: 50 }, "-=0.5");
Rolagem Horizontal:
gsap.to(".painels", {
xPercent: -100 * (painels.length - 1),
ease: "none",
scrollTrigger: {
trigger: ".container",
pin: true,
scrub: 1,
end: "+=" + document.querySelector(".container").offsetWidth
}
});
Parallax Simples:
gsap.to(".bg", {
y: 100,
ease: "none",
scrollTrigger: {
trigger: ".secao",
start: "top bottom",
end: "bottom top",
scrub: true
}
});
Nota: Sempre inclua
gsap.registerPlugin(ScrollTrigger)ao usar as funcionalidades do ScrollTrigger. Para animações básicas sem scroll, o registro não é necessário.