How to Create an Interactive Particle Background in CSS & Canvas
To create an interactive particle background, position a full-bleed HTML5 <canvas> behind your content using position: fixed; z-index: -1; inset: 0; in CSS. Then, render a particle array inside a requestAnimationFrame loop in JavaScript, tracking cursor distance with Math.hypot() to draw dynamic constellation lines and trigger mouse repulsion.
Step 1: The CSS Background Layer
The secret to a smooth background particle effect is ensuring the canvas never traps pointer events intended for links, forms, or buttons. By setting pointer-events: none on the canvas (or selectively capturing mouse moves on a container), your interactive website content remains 100% accessible:
/* Background Canvas Wrapper */
#particle-canvas {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
z-index: -1;
background: #0f0f13;
pointer-events: auto; /* Enable mouse hover tracking */
}
/* Foreground Content */
.hero-content {
position: relative;
z-index: 1;
pointer-events: none; /* Let cursor pass through to canvas */
}
.hero-content a,
.hero-content button {
pointer-events: auto; /* Buttons remain clickable */
}
Step 2: The Particle Class & Physics Loop
Each particle needs position coordinates (x, y), a velocity vector (vx, vy), and a radius. When particles hit the edge of the viewport, simply invert their velocity:
class Particle {
constructor(canvas) {
this.canvas = canvas;
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
this.radius = Math.random() * 2 + 1.2;
this.vx = (Math.random() - 0.5) * 1.5;
this.vy = (Math.random() - 0.5) * 1.5;
}
update() {
this.x += this.vx;
this.y += this.vy;
// Bounce off screen boundaries
if (this.x < 0 || this.x > this.canvas.width) this.vx *= -1;
if (this.y < 0 || this.y > this.canvas.height) this.vy *= -1;
}
draw(ctx) {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = '#6c63ff';
ctx.fill();
}
}
Step 3: Drawing Dynamic Constellation Lines
To draw lines between neighboring particles, compare each particle against every other particle using a nested loop. Using Math.hypot(dx, dy), calculate distance and set the line opacity inversely proportional to the distance:
function connectParticles(particles, ctx, maxDistance = 90) {
for (let i = 0; i < particles.length; i++) {
for (let j = i + 1; j < particles.length; j++) {
const dx = particles[i].x - particles[j].x;
const dy = particles[i].y - particles[j].y;
const dist = Math.hypot(dx, dy);
if (dist < maxDistance) {
const alpha = 1 - (dist / maxDistance);
ctx.strokeStyle = `rgba(167, 139, 250, ${alpha * 0.8})`;
ctx.lineWidth = 0.8;
ctx.beginPath();
ctx.moveTo(particles[i].x, particles[i].y);
ctx.lineTo(particles[j].x, particles[j].y);
ctx.stroke();
}
}
}
}
Next-Level Addons: Elevating Your Particle Background
Once you have baseline canvas particles running, production landing pages rarely stop at simple dots on a flat black screen. Here are three powerful design additions to create a polished, agency-grade presentation:
When building high-performance UI animations or particle systems, my golden rule is: never calculate layout triggers (like getBoundingClientRect() or offsetHeight) inside animation loops. Read measurements once upfront and use CSS transforms or Canvas for buttery 60fps.
Frequently Asked Questions
Practical answers to common questions about canvas particles, mouse interaction physics, and mobile battery performance.
Can you create a particle background in pure CSS without JavaScript?
Yes, but with severe limitations. You can create 20–30 floating particles in pure CSS using multiple box-shadow offsets on a single pseudo-element, or by animating multiple div elements with CSS @keyframes.
However, pure CSS cannot react to cursor movement dynamically, nor can it dynamically draw constellation lines between moving particles. For any interactive background or layouts with more than 40 nodes, HTML5 Canvas is vastly more memory-efficient and avoids DOM thrashing.
How do you make particles interact with the mouse cursor?
Add a mousemove event listener to update an object storing cursor coordinates {x, y}. Inside your particle animation loop, calculate the Euclidean distance between each particle and the cursor.
If the distance is less than your interaction radius (typically 80px to 120px), push the particle away by adding a displacement proportional to (particle.x - mouse.x).
How do particle canvas animations impact mobile battery and performance?
Because distance calculations run in \(O(n^2)\) time, 150 particles require over 11,000 hypotenuse calculations every 16 milliseconds.
To preserve 60fps on mobile:
- Detect viewport width and drop particle count to 25–35 on mobile screens.
- Pause rendering when the tab is hidden using the
document.visibilitychangeevent. - Disable mouse interaction events on devices matching
@media (hover: none).
How do you make the canvas resize responsively without stretching particles?
Always update the canvas internal coordinate buffer width and height properties (canvas.width and canvas.height) inside a debounced window resize listener, rather than scaling with CSS alone. Multiply by window.devicePixelRatio on retina screens to prevent blurriness.
How do you keep text and links clickable when positioned over a particle canvas?
Set pointer-events: none; on the background canvas wrapper so all mouse interactions pass through to underlying buttons. If you want particles to react to mouse movement, listen to mousemove on window or document instead of the canvas element itself.