GSAP- & ScrollTrigger-Entwicklung
Übersicht
GSAP (GreenSock Animation Platform) ist die branchenführende JavaScript-Animationsbibliothek für die Erstellung leistungsstarker, produktionsreifer Animationen. ScrollTrigger ist das leistungsstarke Plugin von GSAP für scrollgesteuerte Animationen. Zusammen ermöglichen sie alles von einfachen UI-Übergängen bis hin zu komplexen, scrollbasierten Storytelling-Erlebnissen.
Grundlegende Konzepte
Die Grundlagen: Tweens
Ein Tween ist eine einzelne Animation von Punkt A nach Punkt B.
// Zu einem Zustand animieren (vom aktuellen Zustand aus)
gsap.to(".box", {
x: 200,
rotation: 360,
duration: 1,
ease: "power2.inOut"
});
// Von einem Zustand animieren (zum aktuellen Zustand hin)
gsap.from(".box", {
opacity: 0,
y: -50,
duration: 0.8
});
// Von-Bis animieren (Anfangs- und Endzustand definieren)
gsap.fromTo(".box",
{ opacity: 0, scale: 0.5 }, // VON
{ opacity: 1, scale: 1, duration: 1 } // BIS
);
Timelines: Animationen sequenzieren
Timelines orchestrieren mehrere Tweens in einer Sequenz oder mit Überlappungen.
const tl = gsap.timeline();
// Standardmäßig nacheinander
tl.to(".box1", { x: 100, duration: 1 })
.to(".box2", { y: 100, duration: 1 })
.to(".box3", { rotation: 360, duration: 1 });
// Mit Labels zur Organisation
tl.addLabel("start")
.to(".hero", { opacity: 1, duration: 1 })
.addLabel("reveal")
.to(".content", { y: 0, duration: 0.8 }, "reveal") // Beginnt beim Label "reveal"
.to(".cta", { scale: 1, duration: 0.5 }, "reveal+=0.5"); // 0,5s nach "reveal"
Der Positionsparameter (Timing in Timelines)
Steuern Sie, wann Animationen innerhalb einer Timeline starten:
const tl = gsap.timeline();
// Standard: Eine nach der anderen
tl.to(".box1", { x: 100 })
.to(".box2", { x: 100 }); // Beginnt, nachdem box1 fertig ist
// Gleichzeitiger Start
tl.to(".box1", { x: 100 })
.to(".box2", { y: 100 }, 0); // Beginnt bei 0 Sekunden
// Relative Positionierung
tl.to(".box1", { x: 100, duration: 2 })
.to(".box2", { y: 100 }, "-=1"); // Beginnt 1 Sekunde vor dem Ende von box1
.to(".box3", { rotation: 360 }, "+=0.5"); // Beginnt 0,5s nach Ende von box2
// Zu einem bestimmten Zeitpunkt
tl.to(".box1", { x: 100 }, 2.5); // Beginnt bei 2,5 Sekunden
Grundlagen von ScrollTrigger
Einfache Scroll-Animation
gsap.registerPlugin(ScrollTrigger);
gsap.to(".box", {
x: 500,
scrollTrigger: {
trigger: ".box",
start: "top center", // Wenn die Oberkante des Triggers die Mitte des Viewports erreicht
end: "bottom center",
markers: true, // Nur für die Entwicklung – zeigt Start-/Endpositionen an
scrub: true, // Verknüpft die Animation mit der Scrollleiste
toggleActions: "play none none reverse" // onEnter, onLeave, onEnterBack, onLeaveBack
}
});
Start- & Endpositionen
Format: "[Trigger-Position] [Viewport-Position]"
// Übliche Muster
start: "top top" // Trigger-Oberkante trifft Viewport-Oberkante
start: "top center" // Trigger-Oberkante trifft Viewport-Mitte (Standard)
start: "top bottom" // Trigger-Oberkante trifft Viewport-Unterkante
start: "center center" // Trigger-Mitte trifft Viewport-Mitte
// Mit Versätzen
start: "top top+=100" // 100px unterhalb der Viewport-Oberkante
start: "top 80%" // Bei 80% des Viewports
end: "+=500" // 500px nach der Startposition
end: "bottom top" // Trigger-Unterkante trifft Viewport-Oberkante
Scrubbing (Scroll-synchrone Animation)
// Boolean: Direkte Verknüpfung mit der Scrollleiste (sofort)
scrub: true
// Zahl: Verzögerung der Glättung in Sekunden
scrub: 1 // Dauert 1 Sekunde, um zur Scrollleiste "aufzuholen"
scrub: 0.5 // Schnelleres, engeres Gefühl
Toggle-Aktionen
Steuern Sie die Animation an vier Scrollpunkten:
toggleActions: "play pause resume reset"
// onEnter | onLeave | onEnterBack | onLeaveBack
// Aktionen: play, pause, resume, restart, reset, complete, reverse, none
Häufige Muster:
toggleActions: "play none none none" // Einmal abspielen beim Eintritt
toggleActions: "play none none reverse" // Vorwärts abspielen, rückwärts zurückspulen
toggleActions: "play complete reverse reset" // Volle Kontrolle
toggleActions: "restart pause resume pause" // Bei jedem Eintritt neu starten
Häufige Muster
1. Einblenden beim Scrollen
gsap.from(".fade-in", {
opacity: 0,
y: 50,
duration: 1,
scrollTrigger: {
trigger: ".fade-in",
start: "top 80%",
end: "top 50%",
scrub: 1,
once: true // Nur einmal animieren
}
});
2. Element beim Scrollen fixieren
ScrollTrigger.create({
trigger: ".panel",
start: "top top",
end: "+=500", // Für 500px Scrollen fixieren
pin: true,
pinSpacing: true // Abstand hinzufügen (Standard: true)
});
3. Horizontaler Scrollbereich
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. Parallax-Effekt
// Langsamere Bewegung (Hintergrundebene)
gsap.to(".bg", {
y: 200,
ease: "none",
scrollTrigger: {
trigger: ".section",
start: "top bottom",
end: "bottom top",
scrub: true
}
});
// Schnellere Bewegung (Vordergrundebene)
gsap.to(".fg", {
y: -100,
ease: "none",
scrollTrigger: {
trigger: ".section",
start: "top bottom",
end: "bottom top",
scrub: true
}
});
5. Scrollgetriggerte Timeline
const tl = gsap.timeline({
scrollTrigger: {
trigger: ".container",
start: "top top",
end: "+=500",
scrub: 1,
pin: true,
snap: {
snapTo: "labels", // An Timeline-Labels einrasten
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. Batch-Animationen (mehrere Elemente)
// Durch mehrere Elemente iterieren
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
}
});
});
// Oder mit 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. Gestaffelte Animationen
gsap.from(".item", {
y: 50,
opacity: 0,
duration: 0.8,
stagger: 0.1, // 0,1s zwischen jedem Element
scrollTrigger: {
trigger: ".grid",
start: "top 80%"
}
});
// Fortgeschrittener Stagger
gsap.from(".item", {
scale: 0,
duration: 1,
stagger: {
each: 0.1,
from: "center", // "start", "center", "end", "edges" oder Indexnummer
grid: "auto", // Für Grid-Layouts
ease: "power2.inOut"
}
});
Integrationsmuster
Mit Three.js / WebGL
import * as THREE from 'three';
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
gsap.registerPlugin(ScrollTrigger);
// Kamera animieren
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)
}
});
// Mesh-Rotation animieren
gsap.to(mesh.rotation, {
y: Math.PI * 2,
scrollTrigger: {
trigger: "#section3",
start: "top bottom",
end: "bottom top",
scrub: true
}
});
// Materialeigenschaften animieren
gsap.to(material, {
opacity: 0,
scrollTrigger: {
trigger: "#section4",
start: "top center",
end: "center center",
scrub: 1
}
});
Mit React (useGSAP-Hook)
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 }); // Scoping für Bereinigung
return (
<div ref={container}>
<div ref={box} className="box">Animierte Box</div>
</div>
);
}
Timeline in React teilen
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" />;
}
Locomotive-Scroll-Integration
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();
Fortgeschrittene Techniken
Bildsequenz-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
});
Sanftes Scrollen zu einem Element
gsap.registerPlugin(ScrollToPlugin);
// Zu Element scrollen
gsap.to(window, {
duration: 1,
scrollTo: "#section2",
ease: "power2.inOut"
});
// Mit Versatz
gsap.to(window, {
duration: 1.5,
scrollTo: { y: "#section2", offsetY: 50 },
ease: "expo.inOut"
});
// Horizontales Scrollen
gsap.to(".container", {
duration: 2,
scrollTo: { x: 1000, autoKill: true }
});
Bedingte Animationen (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
}
});
},
// Mobil
"(max-width: 799px)": function() {
gsap.to(".box", {
y: 200,
scrollTrigger: {
trigger: ".box",
start: "top 80%",
scrub: 1
}
});
}
});
Best Practices für die Leistung
1. CSS will-change verwenden
.animated-element {
will-change: transform, opacity;
}
2. Repaints begrenzen
// Gut: Transform/Opacity animieren (GPU-beschleunigt)
gsap.to(".box", { x: 100, opacity: 0.5 });
// Vermeiden: Layout-Eigenschaften animieren
// gsap.to(".box", { width: 500, height: 300 }); // Verursacht Reflow
3. ScrollTrigger freigeben
// Einzelnen Trigger beenden
const trigger = ScrollTrigger.create({ /* ... */ });
trigger.kill();
// Alle Trigger beenden
ScrollTrigger.getAll().forEach(t => t.kill());
// In React mit Bereinigung
useGSAP(() => {
const tween = gsap.to(".box", { /* ... */ });
return () => {
tween.kill();
};
}, []);
4. Resize entprellen
ScrollTrigger erledigt dies automatisch, aber für benutzerdefinierte Resize-Logik:
let resizeTimer;
window.addEventListener("resize", () => {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(() => {
ScrollTrigger.refresh();
}, 250);
});
5. invalidateOnRefresh verwenden
Für dynamische Werte, die sich bei Größenänderung ändern:
gsap.to(".box", {
x: () => window.innerWidth / 2, // Dynamischer Wert
scrollTrigger: {
trigger: ".box",
start: "top center",
invalidateOnRefresh: true // x bei Größenänderung neu berechnen
}
});
Häufige Fallstricke
1. Mehrere Tweens auf demselben Element
// Problem: Der zweite Tween kollidiert mit dem ersten
gsap.to('h1', { x: 100, scrollTrigger: { /* ... */ } });
gsap.to('h1', { x: 200, scrollTrigger: { /* ... */ } }); // Springt!
// Lösung 1: fromTo verwenden
gsap.fromTo('h1', { x: 100 }, { x: 200, scrollTrigger: { /* ... */ } });
// Lösung 2: immediateRender: false verwenden
gsap.to('h1', { x: 200, immediateRender: false, scrollTrigger: { /* ... */ } });
// Lösung 3: ScrollTrigger auf Timeline anwenden
const tl = gsap.timeline({ scrollTrigger: { /* ... */ } });
tl.to('h1', { x: 100 })
.to('h1', { x: 200 });
2. Keine Schleifen für mehrere Elemente
// Falsch: Alle auf einmal animieren
gsap.to('.section', {
y: -100,
scrollTrigger: { trigger: '.section', scrub: true }
});
// Richtig: Schleife für individuelle Trigger
gsap.utils.toArray('.section').forEach(section => {
gsap.to(section, {
y: -100,
scrollTrigger: { trigger: section, scrub: true }
});
});
3. Vergessen, Plugins zu registrieren
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
import { ScrollToPlugin } from 'gsap/ScrollToPlugin';
gsap.registerPlugin(ScrollTrigger, ScrollToPlugin);
4. ScrollTrigger-Mehrfachinitialisierung in SPA
// Problem: ScrollTrigger wird bei jedem Seitenwechsel neu erstellt
// Lösung: Bereinigen beim Verlassen der Komponente
// React mit useGSAP (automatische Bereinigung)
useGSAP(() => {
const ctx = gsap.context(() => {
ScrollTrigger.create({ /* ... */ });
});
return () => ctx.revert(); // Bereinigt alle in diesem Kontext erstellten Trigger
});