Ứng dụng
Phân tích theo các bước

Cách sử dụng css thông thường
Bước 1: Cập nhật HTML/JSX
<main className="items-center pt-16 pb-4">
<div className="spacer"></div>
<div className="container">
<div className="box box-red">Đỏ</div>
<div className="box box-blue">Xanh</div>
<div className="box box-green">Lá</div>
<div className="box box-purple">Tím</div>
</div>
</main>
Bước 2.1: Thêm và gỡ class show sử dụng useEffect để xử lý IntersectionObserver
IntersectionObserver
useEffect(() => {
const boxes = document.querySelectorAll('.box');
const observer = new IntersectionObserver(
(entries) => {
entries.forEach(entry => {
const el = entry.target;
if (entry.isIntersecting) {
el.classList.add('show');
} else {
el.classList.remove('show');
}
});
},
{
threshold: Array.from({ length: 11 }, (_, i) => i / 10), // 0, 0.1, 0.2,...1
}
);
boxes.forEach(box => observer.observe(box));
return () => boxes.forEach(box => observer.unobserve(box));
}, []);
Bước 2.2 Thêm setTimeout
khi rời khỏi Giúp tránh việc lập tức xóa show
, tạo cảm giác trơn tru:
setTimeout
khi rời khỏi Giúp tránh việc lập tức xóa show
, tạo cảm giác trơn tru:useEffect(() => {
const boxes = document.querySelectorAll('.box');
const timeoutMap = new Map();
const observer = new IntersectionObserver(
(entries) => {
entries.forEach(entry => {
const el = entry.target;
if (entry.isIntersecting) {
clearTimeout(timeoutMap.get(el)); // Hủy bỏ nếu có timeout đang chờ xóa
el.classList.add('show');
} else {
// Trì hoãn việc xóa class
const timeoutId = setTimeout(() => {
el.classList.remove('show');
}, 300); // ví dụ 300ms sau mới xóa
timeoutMap.set(el, timeoutId);
}
});
},
{
threshold: Array.from({ length: 11 }, (_, i) => i / 10),
}
);
boxes.forEach(box => observer.observe(box));
return () => {
boxes.forEach(box => observer.unobserve(box));
timeoutMap.forEach(timeoutId => clearTimeout(timeoutId));
};
}, []);
Bước 3: Thêm CSS
.spacer {
height: 100vh;
}
.box {
opacity: 0;
transform: translateY(20px);
transition: opacity 0.5s ease, transform 0.5s ease;
}
.box.show {
opacity: 1;
transform: translateY(0);
}
app\welcome\welcome.tsx
import { useEffect } from 'react';
export function Welcome() {
useEffect(() => {
const boxes = document.querySelectorAll('.box');
const timeoutMap = new Map();
const observer = new IntersectionObserver(
(entries) => {
entries.forEach(entry => {
const el = entry.target;
if (entry.isIntersecting) {
clearTimeout(timeoutMap.get(el)); // Hủy bỏ nếu có timeout đang chờ xóa
el.classList.add('show');
} else {
// Trì hoãn việc xóa class
const timeoutId = setTimeout(() => {
el.classList.remove('show');
}, 300); // ví dụ 300ms sau mới xóa
timeoutMap.set(el, timeoutId);
}
});
},
{
threshold: Array.from({ length: 11 }, (_, i) => i / 10),
}
);
boxes.forEach(box => observer.observe(box));
return () => {
boxes.forEach(box => observer.unobserve(box));
timeoutMap.forEach(timeoutId => clearTimeout(timeoutId));
};
}, []);
return (
<main className="items-center pt-16 pb-4">
<div className="spacer"></div>
<div className="container-flex">
<div className="box box-red">Đỏ</div>
<div className="box box-blue">Xanh</div>
<div className="box box-green">Lá</div>
<div className="box box-purple">Tím</div>
</div>
</main>
);
}
app\app.css
@import "tailwindcss";
.spacer {
height: 100vh;
}
.box {
width: 120px;
height: 120px;
border-radius: 12px;
color: white;
font-weight: bold;
opacity: 0;
transform: translateY(30px);
transition: opacity 0.6s ease, transform 0.6s ease;
}
.box-red {
background-color: #e74c3c;
}
.box-blue {
background-color: #3498db;
}
.box-green {
background-color: #2ecc71;
}
.box-purple {
background-color: #9b59b6;
}
.box.show {
opacity: 1;
transform: translateY(0);
}
Cách sử dụng tailwind
1. Tailwind CSS: Định nghĩa lớp fade-in
fade-in
// tailwind.config.js
module.exports = {
content: ['./index.html', './src/**/*.{js,ts,jsx,tsx}'],
theme: {
extend: {
keyframes: {
'fade-in-up': {
'0%': { opacity: '0', transform: 'translateY(20px)' },
'100%': { opacity: '1', transform: 'translateY(0)' },
},
},
animation: {
'fade-in-up': 'fade-in-up 0.6s ease-out forwards',
},
},
},
plugins: [],
}
2. CSS thêm class ẩn ban đầu
/* src/index.css hoặc trong component nếu scoped */
.box {
@apply opacity-0 translate-y-5 transition-all duration-700 ease-out;
}
.box.show {
@apply opacity-100 translate-y-0;
}
Hoặc nếu dùng animation Tailwind custom ở trên:
.box {
@apply opacity-0;
}
.box.show {
@apply animate-fade-in-up;
}
Với tailwind css mới bạn khai báo app\app.css
@import "tailwindcss";
.spacer {
height: 100vh;
}
@theme {
--animate-fade-in-up: fade-in-up 1s ease-in-out;
@keyframes fade-in-up {
0% {
opacity: 0;
transform: translateY(20px);
}
100% {
opacity: 1;
transform: translateY(0)
}
}
}
.box-red {
background-color: #e74c3c;
}
.box-blue {
background-color: #3498db;
}
.box-green {
background-color: #2ecc71;
}
.box-purple {
background-color: #9b59b6;
}
.box {
@apply opacity-0;
}
.box.show {
@apply animate-fade-in-up;
}
3. JSX Component với IntersectionObserver (React)
import { useEffect } from 'react';
const MyComponent = () => {
useEffect(() => {
const boxes = document.querySelectorAll('.box');
const observer = new IntersectionObserver(
entries => {
entries.forEach(entry => {
const el = entry.target;
if (entry.isIntersecting && entry.intersectionRatio >= 0.1) {
el.classList.add('show');
} else if (entry.intersectionRatio < 0.1) {
el.classList.remove('show');
}
});
},
{
threshold: Array.from({ length: 11 }, (_, i) => i / 10), // 0 → 1
}
);
boxes.forEach(box => observer.observe(box));
return () => boxes.forEach(box => observer.unobserve(box));
}, []);
return (
<main className="items-center pt-16 pb-4">
<div className="spacer h-screen" />
<div className="container space-y-8">
<div className="box bg-red-500 text-white p-6 rounded-xl shadow-md">Đỏ</div>
<div className="box bg-blue-500 text-white p-6 rounded-xl shadow-md">Xanh</div>
<div className="box bg-green-500 text-white p-6 rounded-xl shadow-md">Lá</div>
<div className="box bg-purple-500 text-white p-6 rounded-xl shadow-md">Tím</div>
</div>
</main>
);
};
export default MyComponent;
😍 4. Mở rộng thêm để hỗ trợ animate delay theo thứ tự (kiểu stagger effect) khi scroll đến không

Tuyệt! Hãy mở rộng code của bạn để có hiệu ứng staggered animation
– tức là các phần tử xuất hiện dần dần theo thứ tự, giống như slide trong hero hoặc gallery đẹp mắt.
Ý tưởng:
Khi các .box
trở nên visible, ta sẽ:
Thêm class
show
để kích hoạt animation.Gán delay tăng dần bằng
style.animationDelay = ...
(hoặcstyle.transitionDelay
nếu dùngtransition
).
✅ Cập nhật Tailwind config (nếu dùng animate-fade-in-up
)
animate-fade-in-up
)Đã có sẵn:
extend: {
keyframes: {
'fade-in-up': {
'0%': { opacity: '0', transform: 'translateY(20px)' },
'100%': { opacity: '1', transform: 'translateY(0)' },
},
},
animation: {
'fade-in-up': 'fade-in-up 0.6s ease-out forwards',
},
},
✅ CSS (Tailwind class)
.box {
@apply opacity-0;
}
.box.show {
@apply animate-fade-in-up;
}
✅ JavaScript (với stagger effect)
import { useEffect } from 'react';
const MyComponent = () => {
useEffect(() => {
const boxes = document.querySelectorAll('.box');
const observer = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
const el = entry.target as HTMLElement;
const allVisibleBoxes = Array.from(boxes).filter((b) => {
const rect = b.getBoundingClientRect();
return rect.top < window.innerHeight && rect.bottom > 0;
});
if (entry.isIntersecting && entry.intersectionRatio >= 0.1) {
// Tính thứ tự để delay
const index = allVisibleBoxes.indexOf(el);
// Gán delay động
el.style.animationDelay = `${index * 150}ms`;
el.classList.add('show');
} else if (entry.intersectionRatio < 0.1) {
el.classList.remove('show');
el.style.animationDelay = '0ms';
}
});
},
{
threshold: Array.from({ length: 11 }, (_, i) => i / 10),
}
);
boxes.forEach((box) => observer.observe(box));
return () => boxes.forEach((box) => observer.unobserve(box));
}, []);
return (
<main className="items-center pt-16 pb-4">
<div className="spacer h-screen" />
<div className="container space-y-8">
<div className="box bg-red-500 text-white p-6 rounded-xl shadow-md">Đỏ</div>
<div className="box bg-blue-500 text-white p-6 rounded-xl shadow-md">Xanh</div>
<div className="box bg-green-500 text-white p-6 rounded-xl shadow-md">Lá</div>
<div className="box bg-purple-500 text-white p-6 rounded-xl shadow-md">Tím</div>
</div>
</main>
);
};
export default MyComponent;
intersectionRatio
là tỷ lệ phần tử đang hiển thị so với toàn bộ kích thước của nó (giá trị từ 0
đến 1
).
✅ Hiệu ứng đạt được:
Khi cuộn đến
.box
, chúng lần lượt hiện lên với delay0ms
,150ms
,300ms
…Khi cuộn ra ngoài, chúng fade-out đồng thời
Mượt, tự nhiên, dễ custom!
🔧 Mẹo mở rộng:
Thay
150ms
bằng biến nhưbaseDelay
để dễ tùy chỉnhDùng
data-index
để kiểm soát thứ tự nếu cầnDùng
transition-delay
nếu bạn muốn dùng@apply transition-*
thay vì animation
Làm thêm phiên bản dùng GSAP dùng React để animation nâng cao hơn
Tuyệt vời! Dưới đây là phiên bản nâng cao sử dụng GSAP (GreenSock Animation Platform) trong React để tạo hiệu ứng scroll-triggered stagger animation – rất mượt, chuyên nghiệp hơn so với chỉ dùng CSS.
✅ 1. Cài đặt GSAP và ScrollTrigger
npm install gsap
Sau đó, trong code bạn register plugin ScrollTrigger
.
✅ 2. React Component với GSAP + Stagger Scroll Animation
timport { useEffect, useRef } from 'react';
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
gsap.registerPlugin(ScrollTrigger);
const GSAPBoxes = () => {
const containerRef = useRef(null);
useEffect(() => {
const boxes = gsap.utils.toArray('.box');
gsap.from(boxes, {
opacity: 0,
y: 40,
duration: 0.8,
ease: 'power3.out',
stagger: 0.2,
scrollTrigger: {
trigger: containerRef.current,
start: 'top 80%',
toggleActions: 'play none none reverse', // fade out when scrolled back
},
});
}, []);
return (
<main className="pt-16 pb-4">
<div className="spacer h-screen" />
<div ref={containerRef} className="container space-y-8">
<div className="box bg-red-500 text-white p-6 rounded-xl shadow-md">Đỏ</div>
<div className="box bg-blue-500 text-white p-6 rounded-xl shadow-md">Xanh</div>
<div className="box bg-green-500 text-white p-6 rounded-xl shadow-md">Lá</div>
<div className="box bg-purple-500 text-white p-6 rounded-xl shadow-md">Tím</div>
</div>
</main>
);
};
export default GSAPBoxes;
✅ 3. Tùy chọn CSS (cho mượt ban đầu)
/* index.css */
.box {
will-change: transform, opacity;
}
✅ Giải thích:
gsap.from(...)
Animate các .box
từ opacity: 0
và y: 40px
stagger: 0.2
Delay mỗi box 0.2 giây → tạo hiệu ứng "xuất hiện theo hàng"
ScrollTrigger
Kích hoạt animation khi scroll đến
toggleActions: 'play none none reverse'
Khi rời khỏi viewport, các box sẽ fade out ngược
✅ Muốn nâng cao thêm?
📦 Animate từng nhóm khi scroll xuống sâu hơn
🔁 Lặp lại animation mỗi lần scroll (dùng
toggleActions
)🧲 Kết hợp GSAP + Tailwind +
clipPath
,scale
, v.v.
✅ Khi nào dùng GSAP thay vì CSS?
Hiệu ứng đơn giản: fade, slide
Các hiệu ứng nâng cao: timeline, physics, scrub, delay
Nhẹ, nhanh, native với Tailwind
Cần kiểm soát sâu: khi bắt đầu, khi kết thúc, trigger phức tạp
Không cần thư viện ngoài
Sẵn sàng tải thêm GSAP
để có UX nâng cao
Build thêm ví dụ multi-section scroll animation với GSAP trong React
Tuyệt! Dưới đây là một ví dụ multi-section scroll animation dùng GSAP + ScrollTrigger trong React.
Bạn sẽ thấy:
Mỗi section animate khi cuộn tới
Các section slide lên + fade-in
Có thể mở rộng thêm timeline, scrub, parallax v.v.
✅ 1. Cài đặt
npm install gsap
✅ 2. Tạo Component: MultiSectionScroll.tsx
MultiSectionScroll.tsx
import { useEffect, useRef } from 'react';
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
gsap.registerPlugin(ScrollTrigger);
const sections = [
{ id: 1, color: 'bg-red-500', label: 'Section 1' },
{ id: 2, color: 'bg-blue-500', label: 'Section 2' },
{ id: 3, color: 'bg-green-500', label: 'Section 3' },
{ id: 4, color: 'bg-purple-500', label: 'Section 4' },
];
const MultiSectionScroll = () => {
const containerRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const sectionEls = gsap.utils.toArray('.section') as HTMLElement[];
sectionEls.forEach((el, index) => {
gsap.fromTo(
el,
{ opacity: 0, y: 50 },
{
opacity: 1,
y: 0,
duration: 0.8,
ease: 'power3.out',
scrollTrigger: {
trigger: el,
start: 'top 80%',
toggleActions: 'play none none reverse',
markers: false, // set true for debug
},
}
);
});
}, []);
return (
<div ref={containerRef} className="space-y-32 py-20">
{sections.map((s) => (
<section
key={s.id}
className={`section ${s.color} text-white text-3xl font-bold h-[80vh] flex items-center justify-center rounded-2xl shadow-lg mx-4`}
>
{s.label}
</section>
))}
</div>
);
};
export default MultiSectionScroll;
✅ 3. Styles (Tailwind)
/* You can also use global styles if needed */
.section {
will-change: transform, opacity;
}
✅ Kết quả:
4 Section xuất hiện khi cuộn tới.
Mỗi section fade-in + slide-up riêng biệt.
Reverse animation khi cuộn ngược lại (nếu cần).
Rất mượt và chuyên nghiệp với GSAP.
✅ Mở rộng gợi ý:
Parallax scroll effect
Dùng ScrollTrigger
+ scrub: true
Stagger từng phần tử trong section
Dùng gsap.timeline()
+ stagger
Fixed background scroll reveal
Dùng pin
của ScrollTrigger
Animate ảnh, tiêu đề, text riêng
Tách selector & gán timeline riêng
— Nếu bạn muốn mình build một landing page kiểu "scroll storytelling" với GSAP (sticky + animation từng phần + số đếm + ảnh phóng to), mình có thể làm mẫu hoàn chỉnh.
Tuyệt! Hãy cùng xây dựng một landing page dạng scroll storytelling với các kỹ thuật nâng cao từ GSAP + React.
🎯 Mục tiêu:
Hero section (fade-in)
Scroll xuống:
Section 1: ảnh zoom + text hiện
Section 2: số đếm (counter) khi visible
Section 3: sticky + scroll reveal
Sử dụng
GSAP + ScrollTrigger + Timeline
✅ 1. Cài đặt
npm install gsap
✅ 2. File ScrollStory.tsx
– Landing page
ScrollStory.tsx
– Landing pageimport { useEffect, useRef } from 'react';
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
gsap.registerPlugin(ScrollTrigger);
const ScrollStory = () => {
const heroRef = useRef(null);
const zoomRef = useRef(null);
const counterRef = useRef(null);
const stickyRef = useRef(null);
useEffect(() => {
// Hero fade in
gsap.from(heroRef.current, {
opacity: 0,
y: -30,
duration: 1,
ease: 'power3.out',
});
// Zoom image
gsap.from(zoomRef.current, {
scale: 0.8,
opacity: 0,
duration: 1,
scrollTrigger: {
trigger: zoomRef.current,
start: 'top 80%',
toggleActions: 'play none none reverse',
},
});
// Counter animation
const counterEl = counterRef.current as HTMLElement;
let counterTriggered = false;
ScrollTrigger.create({
trigger: counterEl,
start: 'top 80%',
onEnter: () => {
if (!counterTriggered) {
const updateCount = () => {
let count = 0;
const target = 100;
const increment = 2;
const interval = setInterval(() => {
count += increment;
counterEl.innerText = count.toString();
if (count >= target) clearInterval(interval);
}, 20);
};
updateCount();
counterTriggered = true;
}
},
});
// Sticky + scroll-reveal
gsap.from(stickyRef.current, {
y: 100,
opacity: 0,
duration: 1,
scrollTrigger: {
trigger: stickyRef.current,
start: 'top 60%',
end: 'bottom top',
scrub: true,
pin: true,
},
});
}, []);
return (
<div className="font-sans text-gray-900 leading-relaxed">
<section
ref={heroRef}
className="h-screen flex items-center justify-center bg-gradient-to-br from-indigo-500 to-purple-600 text-white text-5xl font-bold"
>
Chào mừng bạn đến Landing Page 🎉
</section>
<section className="h-screen flex items-center justify-center bg-white">
<div ref={zoomRef} className="max-w-md">
<img
src="https://source.unsplash.com/600x400/?nature"
alt="Zoom image"
className="rounded-xl shadow-lg"
/>
<p className="mt-6 text-center text-xl font-semibold">Khám phá thiên nhiên</p>
</div>
</section>
<section className="h-screen flex flex-col items-center justify-center bg-gray-100">
<div className="text-4xl font-bold mb-4">Số khách truy cập:</div>
<div
ref={counterRef}
className="text-6xl font-extrabold text-indigo-600"
>
0
</div>
</section>
<section className="h-screen bg-yellow-100 flex items-center justify-center">
<div
ref={stickyRef}
className="bg-yellow-300 text-3xl font-bold p-8 rounded-xl shadow-md"
>
Nội dung được ghim khi scroll!
</div>
</section>
</div>
);
};
export default ScrollStory;
✅ 3. Kết quả:
Hero
Fade-in khi page load
Zoom section
Ảnh scale + fade khi scroll đến
Counter
Số đếm từ 0 → 100 khi phần tử vào viewport
Sticky section
Ghim + di chuyển nội dung theo scroll bằng scrub
+ pin
✅ Gợi ý mở rộng:
👉 Add
gsap.timeline()
cho các animation liên tiếp trong 1 section👉 Add
scrub: true
để tạo hiệu ứng mượt scroll-trigger👉 Add
motion path
,clipPath
,text split
,parallax
…
Bạn muốn mình tiếp tục thêm:
📊 chart animation
🎬 video + scroll sync
📱 responsive animation
🧠 animate SVG path
Tuyệt! Bây giờ ta sẽ mở rộng landing page với animation có tính responsive, tức là:
✅ Mục tiêu:
Animation khác nhau tùy theo kích thước màn hình (VD: mobile vs desktop)
Giữ trải nghiệm mượt mà trên mọi thiết bị
Kết hợp GSAP + ScrollTrigger + Media Queries
✅ 🧠 Cách xử lý responsive với GSAP:
GSAP ScrollTrigger
hỗ trợ media query logic bằng:
ScrollTrigger.matchMedia({
'(min-width: 768px)': () => { /* Desktop animation */ },
'(max-width: 767px)': () => { /* Mobile animation */ },
});
🧪 Ví dụ: Responsive Scroll Animation (GSAP)
import { useEffect, useRef } from 'react';
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
gsap.registerPlugin(ScrollTrigger);
const ResponsiveScroll = () => {
const zoomRef = useRef(null);
useEffect(() => {
ScrollTrigger.matchMedia({
// ✅ Desktop
'(min-width: 768px)': () => {
gsap.fromTo(
zoomRef.current,
{ scale: 0.8, opacity: 0, x: 100 },
{
scale: 1,
opacity: 1,
x: 0,
duration: 1,
ease: 'power3.out',
scrollTrigger: {
trigger: zoomRef.current,
start: 'top 80%',
toggleActions: 'play none none reverse',
},
}
);
},
// ✅ Mobile
'(max-width: 767px)': () => {
gsap.fromTo(
zoomRef.current,
{ scale: 0.9, opacity: 0, y: 50 },
{
scale: 1,
opacity: 1,
y: 0,
duration: 1,
ease: 'back.out(1.7)',
scrollTrigger: {
trigger: zoomRef.current,
start: 'top 85%',
toggleActions: 'play none none reverse',
},
}
);
},
});
}, []);
return (
<section className="h-screen flex items-center justify-center bg-white">
<div ref={zoomRef} className="max-w-md text-center">
<img
src="https://source.unsplash.com/600x400/?travel"
alt="Travel"
className="rounded-xl shadow-lg mx-auto"
/>
<p className="mt-6 text-xl font-semibold">Khám phá hành trình mới 🌍</p>
</div>
</section>
);
};
export default ResponsiveScroll;
🧩 Giải thích:
Desktop (≥768px)
scale + fade + slide-in từ phải
Mobile (<768px)
scale + fade + slide-up nhẹ
với ease: back.out()
Tối ưu UX
Dễ chịu với thao tác tay trên mobile, mạnh mẽ trên desktop
✅ Pro Tips:
✅ Thay đổi duration/ease theo size
ScrollTrigger.matchMedia({})
✅ Ẩn một số animation trên mobile
Đơn giản return null
hoặc không tạo timeline
✅ Stagger khác nhau
Thêm stagger: 0.3
trong desktop, và stagger: 0.1
trong mobile
✅ Pin section chỉ ở desktop
Pin với start: 'top top', end: '+=1000', pin: true
trong desktop only
✅ Muốn nâng cao hơn?
Kết hợp với
CSS container queries
(sắp phổ biến)Thêm
matchMedia.add()
đểdestroy()
khi thay kích thước màn hìnhKết hợp
Framer Motion
để có spring + tap/drag/hover interaction
Nếu bạn muốn mình:
👉 Kết hợp nhiều section vào 1 demo hoàn chỉnh (có responsive scroll story)
👉 Tạo
video scroll sync
,parallax
,split text animation
cho responsive👉 Export thành một GitHub repo + Live preview
video scroll sync
Tuyệt! Giờ ta sẽ build một ví dụ 🎬 video scroll sync với GSAP + ScrollTrigger + React, nơi video được điều khiển bằng cuộn chuột (scrub) – hiệu ứng thường thấy trong các landing page cao cấp (Apple, Tesla...).
Tuyệt! Giờ ta sẽ build một ví dụ 🎬 video scroll sync với GSAP + ScrollTrigger + React, nơi video được điều khiển bằng cuộn chuột (scrub) – hiệu ứng thường thấy trong các landing page cao cấp (Apple, Tesla...).
🎯 Mục tiêu:
Video không tự play
Người dùng scroll để điều khiển thời gian (time) của video
Có sticky section giữ video khi cuộn
✅ 1. Cài đặt
npm install gsap
✅ 2. Component: VideoScrollSync.tsx
VideoScrollSync.tsx
import { useEffect, useRef } from 'react';
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
gsap.registerPlugin(ScrollTrigger);
const VideoScrollSync = () => {
const containerRef = useRef(null);
const videoRef = useRef<HTMLVideoElement>(null);
useEffect(() => {
const video = videoRef.current;
if (!video) return;
// Đảm bảo video đã tải đủ dữ liệu để có duration
video.addEventListener('loadedmetadata', () => {
const duration = video.duration;
// ScrollTrigger scrub = video progress
gsap.to(video, {
currentTime: duration,
ease: 'none',
scrollTrigger: {
trigger: containerRef.current,
start: 'top top',
end: '+=3000', // chiều cao cuộn để điều khiển toàn bộ video
scrub: true,
pin: true,
anticipatePin: 1,
markers: false, // true để debug
},
});
});
}, []);
return (
<section
ref={containerRef}
className="relative h-screen bg-black flex items-center justify-center overflow-hidden"
>
<video
ref={videoRef}
src="/path-to-your-video.mp4"
className="w-full h-auto max-h-[90vh] rounded-xl shadow-2xl"
muted
preload="auto"
/>
</section>
);
};
export default VideoScrollSync;
✅ 3. Ghi chú quan trọng
video.currentTime
GSAP có thể tween giá trị này để điều khiển playback thủ công
pin: true
Giữ section cố định khi scroll (sticky effect)
end: +=3000
Chiều cao scroll – càng lớn cuộn càng lâu mới hết video
scrub: true
Kéo mượt theo cuộn – không phải bật phát một lần
muted
Trình duyệt chặn autoplay audio nếu không có muted
✅ Đặt file video ở đâu?
Nếu bạn dùng Vite:
Đặt video vào thư mục
public/
Gọi như
src="/your-video.mp4"
Hoặc import video nếu bạn dùng Webpack / file bundler:
import myVideo from './assets/video.mp4';
<video src={myVideo} ... />
✅ Mở rộng nâng cao
📱 Responsive video
Tailwind max-w-[100%]
, max-h-[90vh]
, object-contain
🎬 Trigger nội dung khác theo video progress
Dùng ScrollTrigger
khác với onUpdate: self => ...
🧠 Scroll từ frame → frame (image sequence)
Dùng frame-by-frame
animation thay cho video (nặng hơn)
🎙️ Sync âm thanh / phụ đề
Dùng video.textTracks
+ cue points
✅ Demo Live (nếu muốn)
Muốn mình build bản đầy đủ:
💡 Bắt đầu từ Hero
📽️ Video scroll-sync
✨ Fade text theo đoạn video
📱 Responsive
🌐 Gửi link Live hoặc GitHub
👉 Chỉ cần nói: Export demo scroll-video
Mình build ngay cho bạn!
Last updated
Was this helpful?