Animated particle constellations


Ok, stop staring at those darn dots and start coding!

I saw animations similar to the one above on several websites and liked the simplicity of the concept, so let's recreate it - it will only take 42 lines of code.

At a high level, here's the recipe:

- a couple dozens of random particles are bouncing off of the edges of the Canvas
- calculate the distance between each pair of particles
- if the distance is lower than a pre-set threshold, draw a line between them

Here's the full code and a more detailed explanation is below.

<html>
<body bgcolor=black>
<canvas id="myCanvaswidth="800height="600"></canvas>
<script>
 
function line(particle, particle2) {
  context.beginPath();
  context.moveTo(particle.xparticle.y);
  context.lineTo(particle2.x, particle2.y);
  context.stroke();
}
 
function animate() {
  context.clearRect(00canvas.widthcanvas.height);
  for (let i = 0i < maxParticlesi++) {
    let particle = particles[i];
    context.fillRect(particle.x - particleSize / 2particle.y - particleSize / 2particleSizeparticleSize);
    for (let j = 0j < maxParticlesj++) {
      if (i != j) {
        let particle2 = particles[j];
        let distanceX = Math.abs(particle.x - particle2.x);
        let distanceY = Math.abs(particle.y - particle2.y);
        if (distanceX < threshold && distanceY < threshold) {
          context.lineWidth = ((threshold * 2) - (distanceX + distanceY)) / 50;
          let color = 200 - Math.floor(distanceX + distanceY);
          context.strokeStyle = 'rgb(' + color + ',' + color + ',' + color + ')';
          line(particle, particle2);
        }
      }
    }
    particle.x = particle.x + particle.vx;
    particle.y = particle.y + particle.vy;
    if (particle.x > canvas.width - particleSize || particle.x < particleSize)
      particle.vx = -particle.vx;
    if (particle.y > canvas.height - particleSize || particle.y < particleSize)
      particle.vy = -particle.vy;
  }
  window.requestAnimationFrame(animate);
}
 
let canvas = document.getElementById('myCanvas');
let context = canvas.getContext('2d');
let particles = [];
let particleSize = 4;
let maxParticles = 40;
let threshold = 100;
for (let i = 0i < maxParticlesi++) {
  let particle = {
    xMath.random() * canvas.width,
    yMath.random() * canvas.height,
    vxMath.random(),
    vyMath.random()
  }
  particles.push(particle);
}
context.fillStyle = 'white';
animate();
 
</script>
</body>
</html>


[1-4] HTML setup
[6-11] a function that draws a line between two particles
[13-39] the main animation function:
[14] clear the previous frame
[15-37] for each particle:
[18-27] check with every other particle
[19] make sure you're not checking a particle with itself
[21-22] calculate approximate distance between particles (a sum of differences in the X and Y axles). You could use the actual distance [sqrt(distanceX^2+distanceY^2)], but that just slows things down and is not really visible.
[23] if the distance is lower than the threshold...
[24] ...the width...
[25-26] ...and the color of the line (shade of gray with equal values of the Red, Green and Blue components) depend on the distance. Interestingly, Math.floor is only necessary for iOS - other platforms can handle float.
[31-32] The particle moves in both dimensions
[34-36] Bounce off of the edges
[41-46] Set up the Canvas and parameters.
[47-54] Initialize the particles with random coordinates and speeds.
[57] Action!

Experiment with different parameters, for example maxParticles = 100 and threshold = 40 gives you this:



Check out these programming tutorials:

JavaScript:

Optical illusion (18 lines)

Spinning squares - visual effect (25 lines)

Oldschool fire effect (20 lines)

Fireworks (60 lines)

Animated fractal (32 lines)

Minesweeper game (80 lines)

Physics engine for beginners

Physics engine - interactive sandbox

Physics engine - silly contraption

Starfield (21 lines)

Yin Yang with a twist (4 circles and 20 lines)

Tile map editor (70 lines)

Sine scroller (30 lines)

Turtle graphics

Interactive animated sprites

Image transition effect (16 lines)

Wholla lotta quadratic curves (50 lines)

Your first program in JavaScript: you need 5 minutes and a notepad


Fractals in Excel

Python in Blender 3d:

Domino effect (10 lines)


Wrecking ball effect (14 lines)

3d fractal in Blender Python