Moving nodes, connected with lines of weight based on distance separation.
A Pen by Nicholas C. Raftis III on CodePen.
Moving nodes, connected with lines of weight based on distance separation.
A Pen by Nicholas C. Raftis III on CodePen.
| const nodes = [] | |
| function setup() { | |
| createCanvas(windowWidth, windowHeight) | |
| while (nodes.length < 100) | |
| nodes.push(new Node()) | |
| } | |
| function draw() { | |
| background(51) | |
| for (let n of nodes) | |
| n.move(nodes) | |
| for (let n of nodes) | |
| n.drawConnections(nodes) | |
| for (let n of nodes) | |
| n.draw() | |
| } | |
| class Node { | |
| constructor(x = random(width), y = random(height), | |
| vx = random(-1, 1), vy = random(-1, 1)) { | |
| this.x = x | |
| this.y = y | |
| this.vx = vx | |
| this.vy = vy | |
| this.range = sq(width / 10) | |
| this.color = color( | |
| 0, | |
| random(128, 255), | |
| random(128, 255), | |
| 128 | |
| ) | |
| this.i = Node.createIndex() | |
| } | |
| move(nodes) { | |
| if (this.x < 0) | |
| this.vx = abs(this.vx) | |
| else if (this.x > width) | |
| this.vx = -abs(this.vx) | |
| if (this.y < 0) | |
| this.vy = abs(this.vy) | |
| else if (this.y > height) | |
| this.vy = -abs(this.vy) | |
| this.x += this.vx | |
| this.y += this.vy | |
| } | |
| draw() { | |
| noFill() | |
| stroke(this.color) | |
| strokeWeight(10) | |
| point(this.x, this.y) | |
| } | |
| drawConnections(nodes) { | |
| for (let i = this.i + 1; i < nodes.length; i++) { | |
| let n = nodes[i] | |
| let d = sq(this.x - n.x) + sq(this.y - n.y) | |
| if (d > this.range) | |
| continue | |
| noFill() | |
| stroke(lerpColor(this.color, n.color, 0.5)) | |
| strokeWeight(map(d, 0, this.range, 5, 0)) | |
| line(this.x, this.y, n.x, n.y) | |
| } | |
| } | |
| static createIndex() { | |
| if (Node.i === undefined) | |
| Node.i = 0 | |
| return Node.i++ | |
| } | |
| } |
| <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.7/p5.min.js"></script> |