Tracking the Cursor with Framer Motion
Interactive websites that respond to user movements feel alive and engaging. One way to achieve this is cursor tracking, where elements react to the position of the mouse. This technique can create 3D tilts, parallax effects, or subtle movements that make your UI feel more dynamic.
In this article, we'll explore how to implement a 3D tilting box using Framer Motion. We'll start by understanding the concept, then dive into step-by-step coding with explanations.
How Cursor Tracking Works
The idea is simple:
- Track the cursor’s
xandypositions relative to a container. - Store these positions as motion values in Framer Motion.
- Map these values to transforms like
rotateX,rotateY, ortranslateZ. - Apply these transforms to your element to make it respond dynamically.
By the end of this tutorial, you'll have a small, reusable cursor-tracking component ready for your React projects.
Step 1: Setting Up the Project
npm install motion
Step 2: Create the Cursor Tracker Component
Create a new file TrackingTheCursor.jsx (or .tsx if using TypeScript).
Here’s the basic structure:
Loading...
Step 3: Understanding the Code
useMotionValue: Creates reactive values for the x and y positions of the cursor. These values can be smoothly animated.useSpring: Wraps motion values with a spring for smoother movement. It controls how fast and bouncy the animation feels.useEffect+mousemove:
- Adds an event listener to track the cursor.
- Updates
mouseXandmouseYwhenever the cursor moves. - Cleans up the listener when the component unmounts.
motion.div: This is the element that follows the cursor. Itsxandyare bound to our spring values. Styling makes it a small semi-transparent circle and ensures it doesn't interfere with pointer events.
🎉 Conclusion
By following these steps, you now have a fully functional cursor-tracking animation using Motion. This small interactive feature can dramatically enhance user engagement and make your website feel modern and dynamic.
Experiment with spring parameters, colors, and sizes to create unique effects that match your website’s style.