Skip to content

Commit 228a13b

Browse files
committed
Add scroll tracking and effect to WebGLBackground component
1 parent 6cd0f0d commit 228a13b

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

src/components/WebGLBackground.tsx

+30
Original file line numberDiff line numberDiff line change
@@ -45,19 +45,48 @@ export function WebGLBackground() {
4545
let mouseX = 0;
4646
let mouseY = 0;
4747

48+
// Scroll tracking
49+
let lastScrollTop = 0;
50+
let scrollDirection = 0;
51+
let scrollVelocity = 0;
52+
const scrollFactor = 0.0001; // Controls how much scroll affects particles
53+
4854
const handleMouseMove = (event: MouseEvent) => {
4955
mouseX = event.clientX / window.innerWidth - 0.5;
5056
mouseY = event.clientY / window.innerHeight - 0.5;
5157
};
5258

59+
const handleScroll = () => {
60+
// Get current scroll position
61+
const st = window.pageYOffset || document.documentElement.scrollTop;
62+
63+
// Determine scroll direction and velocity
64+
scrollDirection = st > lastScrollTop ? 1 : -1;
65+
scrollVelocity = Math.abs(st - lastScrollTop) * scrollFactor;
66+
67+
// Remember the last scroll position
68+
lastScrollTop = st <= 0 ? 0 : st;
69+
};
70+
5371
window.addEventListener('mousemove', handleMouseMove);
72+
window.addEventListener('scroll', handleScroll);
5473

5574
// Animation
5675
const animate = () => {
5776
requestAnimationFrame(animate);
5877

78+
// Base rotation
5979
particlesMesh.rotation.y += 0.0003;
6080
particlesMesh.rotation.x += 0.0003;
81+
82+
// Apply scroll effect
83+
if (scrollDirection !== 0 && scrollVelocity > 0) {
84+
// Move particles based on scroll direction
85+
particlesMesh.position.y += scrollDirection * scrollVelocity;
86+
87+
// Optional: gradually reset scroll velocity for smoother effect
88+
scrollVelocity *= 0.95;
89+
}
6190

6291
// Smooth camera movement based on mouse position
6392
camera.position.x += (mouseX * 0.5 - camera.position.x) * 0.05;
@@ -81,6 +110,7 @@ export function WebGLBackground() {
81110
return () => {
82111
window.removeEventListener('mousemove', handleMouseMove);
83112
window.removeEventListener('resize', handleResize);
113+
window.removeEventListener('scroll', handleScroll);
84114
containerRef.current?.removeChild(renderer.domElement);
85115
particlesGeometry.dispose();
86116
particlesMaterial.dispose();

0 commit comments

Comments
 (0)