Motion: Nodes

Connect moving points into a graph and drag nodes interactively.

Example 1: Auto-Link Nodes

Code

let nodes = [];

function setup() {
  createCanvas(400, 400);
  for (let i = 0; i < 26; i++) {
    nodes.push({ x: random(width), y: random(height), vx: random(-1, 1), vy: random(-1, 1) });
  }
}

function draw() {
  background(250);
  for (const n of nodes) {
    n.x += n.vx; n.y += n.vy;
    if (n.x < 0 || n.x > width) n.vx *= -1;
    if (n.y < 0 || n.y > height) n.vy *= -1;
  }

  stroke(255, 45, 140, 70);
  for (let i = 0; i < nodes.length; i++) {
    for (let j = i + 1; j < nodes.length; j++) {
      let d = dist(nodes[i].x, nodes[i].y, nodes[j].x, nodes[j].y);
      if (d < 80) line(nodes[i].x, nodes[i].y, nodes[j].x, nodes[j].y);
    }
  }

  noStroke();
  fill(30);
  for (const n of nodes) circle(n.x, n.y, 8);
}

Try this: Lower link distance to reveal local clusters.

Open sketch in new tab

Example 2: Drag Nodes

Code

let pts = [];
let active = -1;

function setup() {
  createCanvas(400, 400);
  for (let i = 0; i < 10; i++) pts.push(createVector(random(60, 340), random(60, 340)));
}

function draw() {
  background(255);
  stroke(40, 50, 60, 120);
  for (let i = 0; i < pts.length - 1; i++) line(pts[i].x, pts[i].y, pts[i + 1].x, pts[i + 1].y);

  noStroke();
  for (let i = 0; i < pts.length; i++) {
    fill(i === active ? color(255, 45, 140) : color(30));
    circle(pts[i].x, pts[i].y, 16);
  }
}

function mousePressed() {
  for (let i = 0; i < pts.length; i++) {
    if (dist(mouseX, mouseY, pts[i].x, pts[i].y) < 12) active = i;
  }
}

function mouseDragged() {
  if (active >= 0) pts[active].set(mouseX, mouseY);
}

function mouseReleased() {
  active = -1;
}

Try this: Add labels to each node and drag to reshape the network.

Open sketch in new tab

Resources