To create a gravity-like effect where the dots are attracted toward the mouse pointer, you need to reverse the direction of the displacement calculations in your animation loop. Currently, the dots are being repelled away from the mouse. This is because the direction vector (dx, dy) is calculated from the dot to the mouse, and then that vector is used to move the dot away from the mouse.
Here's how you can modify your code to achieve the desired gravitational effect:
1. Reverse the Direction Vector
In your animate function, find the section where dx, dy, and distance are calculated. Replace the existing code:
const dx = dot.x - mousePosition.current.x;
const dy = dot.y - mousePosition.current.y;
with:
const dx = mousePosition.current.x - dot.x;
const dy = mousePosition.current.y - dot.y;
Explanation:
By swapping the order (mousePosition.current.x - dot.x instead of dot.x - mousePosition.current.x), you reverse the direction vector, so it points from the dot to the mouse, making the dots move towards the mouse, simulating gravity.
2. Use the Updated Direction Vector for Displacement
With the direction vector reversed, the rest of your displacement calculations can remain the same. The dots will now be displaced toward the mouse based on their proximity.
Here's the updated animate function with the changes highlighted:
const animate = () => {
if (!context) return;
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = dotColor; // Color of the dots
for (let i = 0; i < dots.current.length; i++) {
const dot = dots.current[i];
// Reverse the direction vector
const dx = mousePosition.current.x - dot.x;
const dy = mousePosition.current.y - dot.y;
const distance = Math.sqrt(dx * dx + dy * dy);
let displacementX = 0;
let displacementY = 0;
if (distance < effectRadius) {
const angle = Math.atan2(dy, dx);
const strength = (effectRadius - distance) / effectRadius;
displacementX = Math.cos(angle) * strength * maxDisplacement;
displacementY = Math.sin(angle) * strength * maxDisplacement;
}
context.beginPath();
context.arc(
dot.x + displacementX,
dot.y + displacementY,
dotSize, // Radius of each dot
0,
Math.PI * 2
);
context.fill();
}
animationFrameId.current = requestAnimationFrame(animate);
};
3. Test and Adjust Parameters
After making these changes, test the effect in your application. You may want to adjust the effectRadius and maxDisplacement parameters to fine-tune how the dots move toward the mouse. A larger effectRadius will increase the area of influence, while a larger maxDisplacement will make the dots move more towards the mouse.
Full Updated Code:
Here is your complete AnimatedBackground.tsx component with the modifications:
'use client';
import React, { useEffect, useRef } from 'react';
interface AnimatedBackgroundProps {
gridSpacing?: number;
effectRadius?: number;
maxDisplacement?: number;
dotColor?: string;
dotSize?: number;
}
const AnimatedBackground: React.FC<AnimatedBackgroundProps> = ({
gridSpacing = 25,
effectRadius = 500,
maxDisplacement = 10,
dotColor = '#888',
dotSize = 1.5,
}) => {
const canvasRef = useRef<HTMLCanvasElement | null>(null);
const animationFrameId = useRef<number | null>(null);
const dots = useRef<{ x: number; y: number }[]>([]); // Store positions of dots
const mousePosition = useRef<{ x: number; y: number }>({ x: -1000, y: -1000 }); // Initialize off-screen
useEffect(() => {
const canvas = canvasRef.current;
const context = canvas?.getContext('2d');
if (!canvas || !context) return;
let width = window.innerWidth;
let height = window.innerHeight;
canvas.width = width;
canvas.height = height;
// Function to initialize dots
const initializeDots = () => {
const columns = Math.floor(width / gridSpacing) + 1;
const rows = Math.floor(height / gridSpacing) + 1;
// Initialize dots
const dotArray: { x: number; y: number }[] = [];
for (let row = 0; row < rows; row++) {
for (let col = 0; col < columns; col++) {
dotArray.push({ x: col * gridSpacing, y: row * gridSpacing });
}
}
dots.current = dotArray;
};
initializeDots();
// Handle window resize
const handleResize = () => {
width = window.innerWidth;
height = window.innerHeight;
canvas.width = width;
canvas.height = height;
// Reinitialize dots on resize
initializeDots();
};
window.addEventListener('resize', handleResize);
// Handle mouse move
const handleMouseMove = (event: MouseEvent) => {
mousePosition.current = { x: event.clientX, y: event.clientY };
};
window.addEventListener('mousemove', handleMouseMove);
// Animation loop
const animate = () => {
if (!context) return;
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = dotColor; // Color of the dots
for (let i = 0; i < dots.current.length; i++) {
const dot = dots.current[i];
// Reverse the direction vector for gravity effect
const dx = mousePosition.current.x - dot.x;
const dy = mousePosition.current.y - dot.y;
const distance = Math.sqrt(dx * dx + dy * dy);
let displacementX = 0;
let displacementY = 0;
if (distance < effectRadius) {
const angle = Math.atan2(dy, dx);
const strength = (effectRadius - distance) / effectRadius;
displacementX = Math.cos(angle) * strength * maxDisplacement;
displacementY = Math.sin(angle) * strength * maxDisplacement;
}
context.beginPath();
context.arc(
dot.x + displacementX,
dot.y + displacementY,
dotSize, // Radius of each dot
0,
Math.PI * 2
);
context.fill();
}
animationFrameId.current = requestAnimationFrame(animate);
};
animate(); // Start the animation
// Cleanup on unmount
return () => {
window.removeEventListener('resize', handleResize);
window.removeEventListener('mousemove', handleMouseMove);
if (animationFrameId.current !== null) {
cancelAnimationFrame(animationFrameId.current);
}
};
}, [gridSpacing, effectRadius, maxDisplacement, dotColor, dotSize]);
return (
<canvas
ref={canvasRef}
className="absolute inset-0 pointer-events-none"
style={{ display: 'block' }}
/>
);
};
export default AnimatedBackground;
Summary:
- Reverse the direction vector by swapping the subtraction in
dx and dy.
- This reversal changes the displacement direction, making the dots move toward the mouse.
- Test and adjust the parameters (
effectRadius, maxDisplacement, dotSize) to fine-tune the visual effect.
By making these changes, you will create a gravitational effect where the dots are attracted to the mouse pointer, enhancing the interactivity and visual appeal of your animated background.