Magnetic Cursor Effect
An interactive React component that adds a dynamic bubble effect, visually tracking cursor movement in real time.
An interactive React component that adds a dynamic bubble effect, visually tracking cursor movement in real time.
1// @ts-nocheck2'use client';34import React, { useRef, useEffect, useState } from 'react';5import { motion, useMotionValue, useSpring } from 'framer-motion';67const MagneticCursor: React.FC = () => {8const buttonRef = useRef<HTMLButtonElement | null>(null);9const x = useMotionValue(0);10const y = useMotionValue(0);11const springX = useSpring(x, { stiffness: 200, damping: 20 });12const springY = useSpring(y, { stiffness: 200, damping: 20 });13const [isHovering, setIsHovering] = useState(false);1415useEffect(() => {16const handleMouseMove = (e: MouseEvent) => {17if (buttonRef.current) {18const button = buttonRef.current.getBoundingClientRect();19const centerX = button.left + button.width / 2;20const centerY = button.top + button.height / 2;21const deltaX = e.pageX - centerX;22const deltaY = e.pageY - centerY;2324const distance = Math.sqrt(deltaX ** 2 + deltaY ** 2);25const magneticDistance = 120; // Distance for magnetic attraction26const attractionStrength = 0.45; // Magnetic strength2728if (distance < magneticDistance) {29const strength = 1 - distance / magneticDistance;30x.set(deltaX * strength * attractionStrength);31y.set(deltaY * strength * attractionStrength);32setIsHovering(true);33} else {34x.set(0);35y.set(0);36setIsHovering(false);37}38}39};4041window.addEventListener('mousemove', handleMouseMove);4243return () => {44window.removeEventListener('mousemove', handleMouseMove);45};46}, [x, y]);4748return (49<div className='relative w-full h-full flex items-center justify-center'>50<motion.button51ref={buttonRef}52className={`px-6 py-3 rounded-lg text-white font-semibold transition-transform ${53isHovering ? 'bg-green-500' : 'bg-green-600'54}`}55style={{56x: springX,57y: springY,58}}59>60Hover on me!61</motion.button>62</div>63);64};6566export default MagneticCursor;67
1npm install framer-motion