|
| 1 | +import { useState, useEffect, useRef, useContext } from "react"; |
| 2 | +import { debounce } from "lodash"; |
| 3 | +import { motion } from "framer-motion"; |
| 4 | +import { CursorVariantContext } from "@/context/CursorVariantProvider"; |
| 5 | + |
| 6 | +function Cursor() { |
| 7 | + const { cursorVariant } = useContext(CursorVariantContext); |
| 8 | + |
| 9 | + const [mousePosition, setMousePosition] = useState({ |
| 10 | + x: 0, |
| 11 | + y: 0, |
| 12 | + }); |
| 13 | + |
| 14 | + const cursorRef = useRef(null); |
| 15 | + |
| 16 | + const debouncedMouseMove = debounce((e) => { |
| 17 | + setMousePosition({ |
| 18 | + x: e.clientX, |
| 19 | + y: e.clientY, |
| 20 | + }); |
| 21 | + }, 4); |
| 22 | + |
| 23 | + function mouseMove(e) { |
| 24 | + debouncedMouseMove(e); |
| 25 | + } |
| 26 | + |
| 27 | + useEffect(() => { |
| 28 | + if (cursorRef.current) { |
| 29 | + // cursorRef.current.style.left = `${mousePosition.x}px`; |
| 30 | + // cursorRef.current.style.top = `${mousePosition.y}px`; |
| 31 | + cursorRef.current.animate( |
| 32 | + { |
| 33 | + left: `${mousePosition.x}px`, |
| 34 | + top: `${mousePosition.y}px`, |
| 35 | + }, |
| 36 | + { duration: 400, fill: "forwards" }, |
| 37 | + ); |
| 38 | + } |
| 39 | + window.addEventListener("mousemove", mouseMove); |
| 40 | + |
| 41 | + return () => { |
| 42 | + window.removeEventListener("mousemove", mouseMove); |
| 43 | + }; |
| 44 | + }, [mousePosition]); |
| 45 | + |
| 46 | + const variants = { |
| 47 | + default: { |
| 48 | + mixBlendMode: "normal", |
| 49 | + backgroundColor: "#ffffff", |
| 50 | + }, |
| 51 | + text: { |
| 52 | + height: 150, |
| 53 | + width: 150, |
| 54 | + backgroundColor: "#E76941", |
| 55 | + mixBlendMode: "difference", |
| 56 | + }, |
| 57 | + none: { |
| 58 | + height: 0, |
| 59 | + width: 0, |
| 60 | + }, |
| 61 | + }; |
| 62 | + |
| 63 | + return ( |
| 64 | + <motion.div |
| 65 | + ref={cursorRef} |
| 66 | + className="h-6 w-6 rounded-full border-2 border-background-dark fixed top-0 left-0 -translate-x-1/2 -translate-y-1/2 pointer-events-none z-50" |
| 67 | + variants={variants} |
| 68 | + animate={cursorVariant} |
| 69 | + /> |
| 70 | + ); |
| 71 | +} |
| 72 | + |
| 73 | +export default Cursor; |
0 commit comments