Wie man Redes von Constelaciones mit Physische von Resorte und Atracción in Canvas

Schnellübersicht

Eine red von constelaciones mit physische von resorte modela cada nodo wie eine masa sometida a die ley von elasticidad von Hooke (F = -k * (dist - longitudReposo)). Die partículas conectadas se atraen elásticamente und son atraídas magnéticamente durch der cursor vom ratón, berechnet die fuerzas in cada fotograma und trazando líneas mit grosor dependiente von die tensión.

Interaktive Demo Live-Vorschau
✨ Interactive Spring Network · Elastic Mouse Gravity

Schritt 1: Modelado Physisch vom Nodo mit Geschwindigkeit, Aceleración und Fricción

Erstellt eine Klasse que aplique aceleraciones acumuladas über die Geschwindigkeit und incorpore ein coeficiente von amortiguación (fricción) für estabilizar der sistema.

spring-node.js
class SpringNode {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.vx = 0;
    this.vy = 0;
    this.ax = 0;
    this.ay = 0;
    this.mass = 1;
    this.friction = 0.92;
  }

  applyForce(fx, fy) {
    this.ax += fx / this.mass;
    this.ay += fy / this.mass;
  }

  update() {
    this.vx = (this.vx + this.ax) * this.friction;
    this.vy = (this.vy + this.ay) * this.friction;
    this.x += this.vx;
    this.y += this.vy;
    this.ax = 0;
    this.ay = 0;
  }
}

Schritt 2: Anwendung von die Ley von Hooke zwischen Nodos Enlazados

Berechnet die fuerza elástica zwischen pares von nodos in función von die diferencia zwischen su distancia actual und die longitud von reposo vom resorte.

hooke-law.js
const SPRING_K = 0.003;
const REST_LENGTH = 80;

function applySpringTension(nodeA, nodeB) {
  const dx = nodeB.x - nodeA.x;
  const dy = nodeB.y - nodeA.y;
  const dist = Math.hypot(dx, dy);

  if (dist === 0 || dist > 140) return;

  const displacement = dist - REST_LENGTH;
  const force = displacement * SPRING_K;

  const fx = (dx / dist) * force;
  const fy = (dy / dist) * force;

  nodeA.applyForce(fx, fy);
  nodeB.applyForce(-fx, -fy);
}

Schritt 3: Atracción Gravitacional vom Cursor vom Ratón

Añade eine fuerza que atraiga die nodos circundantes zu die posición actual vom puntero wenn der ratón se desplaza über der lienzo.

mouse-attraction.js
const mouse = { x: null, y: null, force: 0.15, radius: 180 };

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

  if (dist < mouse.radius && dist > 10) {
    const strength = (1 - dist / mouse.radius) * mouse.force;
    node.applyForce((dx / dist) * strength * 2, (dy / dist) * strength * 2);
  }
}

Schritt 4: Renderizado von Nodos und Cuerdas Elásticas in Canvas

Dibuja die partículas und une die enlaces mit eine opacidad und grosor proporcionales a die tensión vom resorte.

render-springs.js
function renderNetwork(nodes, ctx) {
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // Dibujar resortes
  for (let i = 0; i < nodes.length; i++) {
    for (let j = i + 1; j < nodes.length; j++) {
      const dist = Math.hypot(nodes[i].x - nodes[j].x, nodes[i].y - nodes[j].y);
      if (dist < 130) {
        ctx.beginPath();
        ctx.moveTo(nodes[i].x, nodes[i].y);
        ctx.lineTo(nodes[j].x, nodes[j].y);
        ctx.strokeStyle = `rgba(168, 85, 247, ${(1 - dist / 130).toFixed(2)})`;
        ctx.lineWidth = 1;
        ctx.stroke();
      }
    }
  }

  // Dibujar nodos
  nodes.forEach(node => {
    ctx.beginPath();
    ctx.arc(node.x, node.y, 3, 0, Math.PI * 2);
    ctx.fillStyle = '#a855f7';
    ctx.fill();
  });
}

Erweiterte Best Practices & Vertiefung

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

Cell A
Active
Cell B
O(n) SPATIAL HASHING

1. Simulación Elástica mit Amortiguación von Fricción

Im Generator von Redes von Constelaciones und Partículas öffnen →

Movimiento orgánico wo die conexiones se estiran und rebotan naturalmente ohne oscilaciones infinitas.

2. Campo Gravitacional Interaktiv vom Cursor

Im Generator von Redes von Constelaciones und Partículas öffnen →

Arrastra sanftmente racimos von estrellas in torno al cursor simulando ein pozo von gravedad espacial.

Fija nodos in die esquinas für generieren redes tensadas tipo tela von araña tecnológica.

Chaam
Chaams Profi-Tipp

Mein Tipp für den produktiven Einsatz: Teste frühzeitig in mehreren Browsern. Halte die DOM-Hierarchie schlank, optimiere Bildressourcen mit modernen Formaten (WebP/AVIF) und stelle Barrierefreiheit per Tastaturbedienung sicher.

Listo für incorporar physische moleculares elásticas a tus partículas?

Generiert redes von nodos mit resortes interaktive, atracción magnética und amortiguación physische suave.

Im Generator von Redes von Constelaciones und Partículas öffnen ↗

Häufig gestellte Fragen (FAQ)

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

Durch qué es indispensable incluir ein factor von fricción (damping)?

Ohne amortiguación (friction: 0.92), die energía vom sistema se acumularía indefinidamente mit cada fuerza aplicada, haciendo que die partículas aceleraran bis salir despedidas von die Bildschirm.

Qué es die longitud von reposo (rest length)?

Es die distancia ideal in die cual der resorte no ejerce fuerza ni von atracción ni von repulsión. Si die nodos se acercan mehr que diese distancia, se repelen; si se alejan mehr, se atraen.

Wie limitar der número von conexiones durch nodo für verbessern der Performance?

Puedes limitar cada partícula a ein maximal von 3 oder 4 conexiones concurrentes (maxLinks = 4), evitando saturar visualmente der lienzo und reduciendo die cálculos durch fotograma.

Wie afecta dieser Effekt al uso von Speicher in mobile Endgeräte?

Ein grafo von 50 nodos mit physische von resorte ocupa weniger von 2 MB von Speicher RAM und ejecuta weniger von 1,200 operaciones durch fotograma, manteniendo eine fluidez absoluta ohne calentamiento.

Se puede arrastrar ein nodo directamente haciendo clic und arrastrando?

Sí. Puedes detectar si der clic cae a weniger vom radio vom nodo, marcarlo wie isDragging = true und fijar sus coordenadas directamente a die vom ratón mientras dure der arrastre.

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