Particles simulation that interacts with the users' mouse movements.
Demo: https://dynstat.github.io/canvas-particles-simulation/
The code is wrapped in an IIFE (Immediately Invoked Function Expression) to prevent global scope pollution. The main components are:
- Configuration object
- Helper functions
- Particle class
- ParticleSystem class
- Initialization code
const config = {
particleBaseCount: 100,
// ... other configuration options
};
Defines all adjustable parameters for the particle system, including particle counts, sizes, velocities, and visual settings.
- DOM loads and triggers:
document.addEventListener('DOMContentLoaded', () => {
new ParticleSystem('canvas');
});
- ParticleSystem constructor:
- Gets canvas element
- Sets up context
- Initializes properties
- Calls
init()
-
handleResize()
is called to:- Set canvas dimensions
- Apply gradient styling
- Create initial particles
-
Event listeners are set up for:
- Mouse movement
- Window resizing
The main animation loop (animate()
) runs continuously with these steps:
- Clear canvas
- Apply mouse interactions
- Update particle physics
- Draw connections between particles
- Draw particles
- Request next animation frame
-
Constructor: Initializes particle with:
- Random position within canvas
- Random velocity
- Size (radius)
- Push forces (for mouse interaction)
-
applyPhysics: Handles:
- Position updates
- Boundary collisions
- Force friction
- Velocity changes
-
Mouse Interaction:
applyMouseInteraction()
- Calculates force based on mouse proximity
- Applies push forces to nearby particles
-
Connections:
drawConnections()
- Draws lines between nearby particles
- Controls opacity based on distance
- Limits connections per particle
- Mouse movement → Updates mouse coordinates
- Animation frame starts
- Mouse position → Affects particle push forces
- Particles update positions based on:
- Base velocity
- Push forces
- Boundary collisions
- System draws connections between particles
- System draws updated particle positions
- Process repeats for next frame
- Particles are drawn as circles
- Connections are lines with gradient colors
- Opacity changes based on distance
- Mouse interaction creates a repulsion effect