Wie man Hintergründe von Partículas und Constelaciones Interaktive in Canvas und CSS

Schnellübersicht

Ein Hintergrund interaktiv von partículas in HTML5 Canvas almacena ein arreglo von nodos mit coordenadas (x, und) und velocidades (vx, vy). In cada fotograma von requestAnimationFrame, se actualizan sus posiciones rebotando in die Rahmen vom lienzo und se traza eine línea mit opacidad inversa wenn die distancia euclidiana zwischen dos partículas oder mit respecto al cursor vom ratón es menor a 120 píxeles.

Interaktive Demo (Move cursor over the canvas) 60 FPS
60
2x
85px

Schritt 1: Inicialización vom Lienzo Canvas mit Escalado für Bildschirme Retina

Erstellt der Element <canvas> ajustado al Größe vollständig von die ventana teniendo in cuenta der window.devicePixelRatio für evitar gráficos borrosos.

particle-canvas.js
const canvas = document.getElementById('particleCanvas');
const ctx = canvas.getContext('2d');

function resizeCanvas() {
  const dpr = window.devicePixelRatio || 1;
  canvas.width = window.innerWidth * dpr;
  canvas.height = window.innerHeight * dpr;
  canvas.style.width = `${window.innerWidth}px`;
  canvas.style.height = `${window.innerHeight}px`;
  ctx.scale(dpr, dpr);
}

window.addEventListener('resize', resizeCanvas);
resizeCanvas();

Schritt 2: Estructuración von die Klasse Particle und Bucle Physisch

Define die Klasse que modela cada punto mit posición, Geschwindigkeit aleatoria, radio und método von dibujo in der contexto 2D.

particle-class.js
class Particle {
  constructor(w, h) {
    this.x = Math.random() * w;
    this.y = Math.random() * h;
    this.vx = (Math.random() - 0.5) * 1.2;
    this.vy = (Math.random() - 0.5) * 1.2;
    this.radius = Math.random() * 2 + 1;
  }

  update(w, h) {
    this.x += this.vx;
    this.y += this.vy;

    if (this.x < 0 || this.x > w) this.vx *= -1;
    if (this.y < 0 || this.y > h) this.vy *= -1;
  }

  draw(ctx) {
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
    ctx.fillStyle = '#6366f1';
    ctx.fill();
  }
}

Schritt 3: Cálculo von Distancia Euclidiana und Trazado von Enlaces

Recorre die partículas berechnet die distancia euclidiana zwischen pares. Si die distancia es menor a ein umbral (durch Beispiel 100px), traza eine línea mit opacidad decreciente.

particle-connections.js
const MAX_DIST = 110;

function connectParticles(particles, ctx) {
  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 < MAX_DIST) {
        const opacity = 1 - dist / MAX_DIST;
        ctx.beginPath();
        ctx.moveTo(particles[i].x, particles[i].y);
        ctx.lineTo(particles[j].x, particles[j].y);
        ctx.strokeStyle = `rgba(99, 102, 241, ${(opacity * 0.4).toFixed(2)})`;
        ctx.lineWidth = 1;
        ctx.stroke();
      }
    }
  }
}

Schritt 4: Interacción vom Cursor und Repulsión Dinámica

Registra die coordenadas vom cursor vom ratón für erstellen ein Effekt von atracción oder empuje magnético wenn der puntero se acerca a die partículas.

cursor-physics.js
const mouse = { x: null, y: null, radius: 140 };

window.addEventListener('mousemove', (e) => {
  mouse.x = e.clientX;
  mouse.y = e.clientY;
});

window.addEventListener('mouseleave', () => {
  mouse.x = null;
  mouse.y = null;
});

function applyMouseRepulsion(particle) {
  if (mouse.x === null) return;
  const dx = particle.x - mouse.x;
  const dy = particle.y - mouse.y;
  const dist = Math.hypot(dx, dy);

  if (dist < mouse.radius) {
    const force = (mouse.radius - dist) / mouse.radius;
    particle.x += (dx / dist) * force * 3;
    particle.y += (dy / dist) * force * 3;
  }
}

Erweiterte Best Practices & Vertiefung

Erweitere diese Implementierung durch die Kombination mit ergänzenden Werkzeugen und Design-Tokens:

Particles + Mesh Glow

1. Physische von Tensión von Resorte mit Ley von Hooke

Im Generator von Hintergründe von Partículas und Constelaciones öffnen →

Simulación elástica realista wo die conexiones actúan wie cuerdas mit resistencia und amortiguación.

Particles + Film Grain Overlay

2. Optimización von Partición Espacial (Spatial Hashing)

Im Generator von Hintergründe von Partículas und Constelaciones öffnen →

Divide die Bildschirm in eine cuadrícula virtual reduciendo der coste von comparación von Oder(n²) a Oder(n).

Reduce dinámicamente der conteo von partículas in smartphones für proteger die Akku vom Nutzer.

Chaam
Chaams Profi-Tipp

Beim Entwickeln von performanten UI-Animationen oder Partikelsystemen gilt meine Faustregel: Berechne niemals Layout-Eigenschaften (wie getBoundingClientRect() oder offsetHeight) innerhalb von Animations-Schleifen. Führe Messungen einmalig vorab durch und nutze GPU-beschleunigte CSS-Transforms oder Canvas für stabile 60 fps.

Listo für bauen Partikelnetzwerke und constelaciones interaktive?

Generiert redes moleculares in Canvas mit atracción magnética al cursor, ajustes von densidad und physische fluide a 60 FPS.

Im Generator von Hintergründe von Partículas und Constelaciones öffnen ↗

Häufig gestellte Fragen (FAQ)

Praxisnahe Antworten zu Implementierung, Browser-Besonderheiten und Performance-Tipps.

Durch qué conectar partículas tiene complejidad algorítmica Oder(n²)?

Porque comparar cada partícula mit todas die demás exige realizar (n * (n - 1)) / 2 cálculos von distancia. Mit 100 partículas se realizan einige 4,950 comprobaciones durch fotograma, das cual es sehr ligero für die CPU modern.

Wie evitar que der canvas consuma Akku wenn der Nutzer cambia von pestaña?

Al verwenden requestAnimationFrame(), die Browser pausan automáticamente die ejecución wenn die pestaña pasa a segundo plano, reduciendo der consumo von GPU a cero nativ.

Was ist der número óptimo von partículas in escritorio und móvil?

Se aconseja zwischen 60 und 90 partículas in Bildschirme von escritorio, und no mehr von 30 a 45 in smartphones für beibehalten 60 FPS estables ohne sobrecalentar der terminal.

Durch qué se nutzt Math.hypot(dx, dy) anstelle von Math.sqrt(dx*dx + dy*dy)?

Math.hypot es eine función native optimizada que previene desbordamientos numéricos und bietet eine sintaxis mucho mehr limpia für berechnen die hipotenusa euclidiana.

Wie colocar contenido interaktiv (Buttons, Texte) encima vom canvas?

Asigna position: fixed; top: 0; left: 0; z-index: -1; pointer-events: none; al Element canvas für que no intercepte die clics über die formularios und enlaces von tu Seite web.

← Zurück zu allen Blog-Artikeln Generator-Studio starten →