Building Constellation Node Networks with Spring Physics & Cursor Attraction in HTML5 Canvas

The Quick Answer

A constellation node network simulates floating stars connected by dynamic line segments when their Euclidean distance falls below a threshold (e.g. 100px). Line opacity is inversely proportional to distance (opacity = 1 - dist / maxDist). By adding Hooke's law spring tension and cursor repulsion, the network behaves like an elastic, tactile spiderweb.

Interactive Demo Live Preview
✨ Interactive Spring Network · Elastic Mouse Gravity

Step 1: Node Class with Velocity and Bounding Physics

Each node maintains 2D position, velocity, radius, and mass. When hitting canvas boundaries, invert velocity vectors to contain particles within the viewport.

constellation-node.js
class Node {
  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.5;
  }
  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;
  }
}

Step 2: Distance Proximity & Dynamic Line Rendering

For every pair of nodes, calculate Euclidean distance using Math.hypot(dx, dy). When distance < threshold, draw a line whose stroke alpha fades smoothly.

constellation-links.js
const MAX_DIST = 110;

function drawConnections(nodes, ctx) {
  for (let i = 0; i < nodes.length; i++) {
    for (let j = i + 1; j < nodes.length; j++) {
      const dx = nodes[i].x - nodes[j].x;
      const dy = nodes[i].y - nodes[j].y;
      const dist = Math.hypot(dx, dy);

      if (dist < MAX_DIST) {
        const alpha = (1 - dist / MAX_DIST) * 0.7;
        ctx.strokeStyle = `rgba(167, 139, 250, ${alpha})`;
        ctx.lineWidth = 0.8;
        ctx.beginPath();
        ctx.moveTo(nodes[i].x, nodes[i].y);
        ctx.lineTo(nodes[j].x, nodes[j].y);
        ctx.stroke();
      }
    }
  }
}

Step 3: Cursor Attraction & Elastic Spring Snapping

Treat the cursor as an active node. When nearby nodes get pulled toward the cursor, apply Hooke's spring physics (F = -k * x) and dampening to avoid unnatural oscillations.

mouse-spring.js
function applyMouseForce(node, mouse, radius = 150) {
  const dx = mouse.x - node.x;
  const dy = mouse.y - node.y;
  const dist = Math.hypot(dx, dy);

  if (dist < radius && dist > 1) {
    const force = (radius - dist) / radius;
    // Gentle repulsion away from cursor
    node.x -= (dx / dist) * force * 3;
    node.y -= (dy / dist) * force * 3;
  }
}

Next-Level Addons: Elevating Your Implementation

Take this technique further by combining it with complementary design token studios and animation tools:

Cell A
Active
Cell B
O(n) SPATIAL HASHING

1. Spatial Hashing for 10x Faster Distance Checks

Explore in Particle Background Studio →

Avoid O(n²) bottlenecks by dividing the screen into a spatial grid hash map. Only check distance between nodes in adjacent buckets, boosting particle count to 500+ at 60fps.

2. Glow Pulses on Triangle Triplets

Explore in Clip-Path Generator →

Detect when three nodes form a closed triangle and render an ambient translucent gradient fill inside the enclosed triangle polygon.

3. Touch Gesture Force Rings on Mobile

Explore in Touch Screen Multi-Touch Diagnostics →

Support multi-touch coordinates on tablets, rendering glowing ripples that repel nearby constellations on finger tap.

Chaam
Chaam's Pro Tip

Here's my golden rule when implementing this in production: test across multiple devices and browsers early. Keep your DOM hierarchy shallow, optimize assets with modern formats (like WebP/AVIF), and verify keyboard navigation for accessibility.

Why I Built the Particle Background Studio

I got tired of guessing values and testing browser quirks in DevTools, so I built this tool to tweak and preview values in real time with 1-click code export.

Open in Particle Background Studio ↗

Frequently Asked Questions

Practical answers to common implementation questions, browser quirks, and performance tips.

Why does constellation canvas lag with more than 150 particles?

The naive nested loop checks distance between every pair, requiring n*(n-1)/2 calculations (150 nodes = 11,175 distance checks per frame). Implement spatial grid partitioning to check only neighboring grid cells, reducing checks to O(n).

How do you scale constellation node counts responsively on mobile?

Base node density on viewport area rather than a fixed number: nodeCount = Math.floor((width * height) / 12000). On a 390px phone, this spawns ~25 nodes; on a 4K monitor, it spawns ~200 nodes.

How do you prevent particles from clustering along screen edges?

Rather than hard bouncing, implement toroidal screen wrapping: when a particle leaves x > width, set x = 0 (and vice-versa). This maintains continuous, isotropic particle distribution.

Can interactive constellation networks be rendered using SVG?

SVG and elements work for up to 30 nodes. Beyond 50 nodes, updating hundreds of SVG DOM element attributes per frame overwhelms the browser render tree, while Canvas 2D renders 200 nodes at 60fps.

How do you pause constellation animations when off-screen?

Wrap your requestAnimationFrame loop with an IntersectionObserver on the canvas element. Cancel the animation frame whenever the canvas is not in the active viewport.

← Back to all blog guides Launch Generator Studio →