const GRID_SIZE = 25; // Size of the grid cells in pixels
const DOT_SIZE = 3; // Size of the dots
const MAGNET_RADIUS = 100; // Radius around the mouse where dots will be affected
const MAGNET_STRENGTH = 15; // How much the dots move towards the mouse
// Generate the grid of dots based on the window size
const createDots = useCallback(() => {
const { innerWidth, innerHeight } = window;
const cols = Math.ceil(innerWidth / GRID_SIZE);
const rows = Math.ceil(innerHeight / GRID_SIZE);
const newDots: Dot[] = [];
code
let id = 0;
for (let y = 0; y <= rows; y++) {
for (let x = 0; x <= cols; x++) {
newDots.push({
id: id++,
x: x * GRID_SIZE,
y: y * GRID_SIZE,
});
}
}
setDots(newDots);
TASK: I want the dots to move off their grid towards the mouse like a magnetic effect whereever teh mouse is.
To achieve the magnetic effect where the dots move off their grid towards the mouse, you'll need to adjust your code to update each dot's position based on the mouse movement. Here's how you can modify your component to create that effect:
Update the Dot Interface: Include offsetX and offsetY properties in your Dot interface to represent the displacement from the dot's original position.
Initialize the Offsets: When creating the dots, initialize offsetX and offsetY to 0.
tsx
newDots.push({
id: id++,
x: x * GRID_SIZE,
y: y * GRID_SIZE,
offsetX: 0,
offsetY: 0,
});
Handle Mouse Movement: In your handleMouseMove function, calculate the offset for each dot based on its distance from the mouse pointer. Update the dots' state with the new offsets.
Complete Updated Code: Here's the full updated component with the changes applied:
tsx
// components/AnimatedBackground.tsx
'use client'; // This directive tells Next.js that this is a client-side component
import React, { useEffect, useState, useCallback } from 'react';
import { motion } from 'framer-motion';
interface Dot {
id: number;
x: number;
y: number;
offsetX: number;
offsetY: number;
}
const GRID_SIZE = 25; // Size of the grid cells in pixels
const DOT_SIZE = 3; // Size of the dots
const MAGNET_RADIUS = 100; // Radius around the mouse where dots will be affected
const MAGNET_STRENGTH = 15; // How much the dots move towards the mouse
const AnimatedBackground: React.FC = () => {
const [dots, setDots] = useState<Dot[]>([]);
// Generate the grid of dots based on the window size
const createDots = useCallback(() => {
const { innerWidth, innerHeight } = window;
const cols = Math.ceil(innerWidth / GRID_SIZE);
const rows = Math.ceil(innerHeight / GRID_SIZE);
const newDots: Dot[] = [];
let id = 0;
for (let y = 0; y <= rows; y++) {
for (let x = 0; x <= cols; x++) {
newDots.push({
id: id++,
x: x * GRID_SIZE,
y: y * GRID_SIZE,
offsetX: 0,
offsetY: 0,
});
}
}
setDots(newDots);
}, []);
useEffect(() => {
createDots();
window.addEventListener('resize', createDots);
return () => {
window.removeEventListener('resize', createDots);
};
}, [createDots]);
// Handle mouse movement
const handleMouseMove = (e: React.MouseEvent) => {
const mouseX = e.clientX;
const mouseY = e.clientY;
const newDots = dots.map((dot) => {
const dx = mouseX - dot.x;
const dy = mouseY - dot.y;
const distance = Math.sqrt(dx * dx + dy * dy);
if (distance < MAGNET_RADIUS) {
// Calculate the offset
const strength = (1 - distance / MAGNET_RADIUS) * MAGNET_STRENGTH;
const offsetX = (dx / distance) * strength;
const offsetY = (dy / distance) * strength;
return {
...dot,
offsetX,
offsetY,
};
} else {
return {
...dot,
offsetX: 0,
offsetY: 0,
};
}
});
setDots(newDots);
};
// Handle mouse leaving the window
const handleMouseLeave = () => {
const newDots = dots.map((dot) => ({
...dot,
offsetX: 0,
offsetY: 0,
}));
setDots(newDots);
};
return (
<div
className="fixed inset-0"
onMouseMove={handleMouseMove}
onMouseLeave={handleMouseLeave}
>
{dots.map((dot) => (
<motion.div
key={dot.id}
className="absolute"
style={{
width: DOT_SIZE,
height: DOT_SIZE,
backgroundColor: '#000',
borderRadius: '50%',
top: 0,
left: 0,
}}
initial={{ x: dot.x, y: dot.y }}
animate={{ x: dot.x + dot.offsetX, y: dot.y + dot.offsetY }}
transition={{ type: 'spring', stiffness: 100, damping: 10 }}
/>
))}
</div>
);
};
export default AnimatedBackground;
Explanation:
State Management: By adding offsetX and offsetY to each dot, you're able to individually control their positions relative to their original grid coordinates.
Mouse Movement Handling: As the mouse moves, the handleMouseMove function recalculates the offsets for each dot that's within the MAGNET_RADIUS. This creates the effect of the dots being attracted to the mouse pointer.
Animation: Using the animate prop in motion.div, the dots smoothly transition to their new positions whenever their offsets change. The transition prop adds a spring animation for a more natural movement.
Performance Consideration: Updating the state for all dots on every mouse move could impact performance, especially with a large number of dots. If you notice any lag, consider throttling the handleMouseMove function using lodash.throttle or a similar utility to limit how often the state updates.
Optional Enhancements:
Throttle Mouse Move Handler: To improve performance, you can throttle the handleMouseMove function:
tsx
import throttle from 'lodash.throttle';
const throttledHandleMouseMove = throttle(handleMouseMove, 20);
// Use throttled function in the event handler
onMouseMove={throttledHandleMouseMove}
Visual Styling: Adjust the DOT_SIZE, GRID_SIZE, and CSS styles to achieve the desired appearance for your dots and grid.
By implementing these changes, your dots should now move towards the mouse cursor in a magnetic fashion, creating the interactive effect you're looking for.