feat(wip parallax test on homepage)
This commit is contained in:
34
resources/js/hooks/use-parallax.ts
Normal file
34
resources/js/hooks/use-parallax.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
|
||||
export function useParallax<T extends HTMLElement>(speed: number = 0.15) {
|
||||
const ref = useRef<T>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const el = ref.current;
|
||||
if (!el) return;
|
||||
|
||||
let rafId: number;
|
||||
let ticking = false;
|
||||
|
||||
const update = () => {
|
||||
el.style.transform = `translateY(${window.scrollY * speed}px)`;
|
||||
ticking = false;
|
||||
};
|
||||
|
||||
const onScroll = () => {
|
||||
if (!ticking) {
|
||||
rafId = requestAnimationFrame(update);
|
||||
ticking = true;
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('scroll', onScroll, { passive: true });
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('scroll', onScroll);
|
||||
cancelAnimationFrame(rafId);
|
||||
};
|
||||
}, [speed]);
|
||||
|
||||
return ref;
|
||||
}
|
||||
Reference in New Issue
Block a user