# 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.



[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