I’m going to show you how to create a mesmerizing generative animation with just a few lines of JavaScript code and the p5.js library. The result? Colorful lines bouncing across the screen, creating organic and hypnotic patterns. SPOILER: The result is here

The Concept

The idea is simple yet powerful: a line travels across the canvas, bouncing off the edges and leaving a colorful trail behind. The magic happens through three key elements: movement, rotation, and dynamic colors.

Breaking Down the Code

Initialization

At startup, we create a 600×600 pixel canvas and place our line at a random position with random velocity. This is what makes each execution unique: no two animations will ever be the same.

x = random(0, width);
y = random(0, height);
speedX = random(-10, 10);
speedY = random(-10, 10);

The Color Magic

The most interesting part of the code is how the colors evolve. The red value depends on the line’s horizontal position, while green depends on its vertical position. Blue stays constant at 255, giving that characteristic cyan tint.

const redVal = map(x, 0, width, 0, 255);
const greenVal = map(y, 0, height, 0, 255);
stroke(redVal, greenVal, 255);

The result: as the line moves right and down, it gradually becomes more yellow. Toward the left and up, it shifts toward cyan. It’s a geometric rainbow drawing itself in real time.

Dynamic Rotation

Instead of drawing a simple horizontal line, the code rotates it based on its vertical position. The further down the line goes, the more it spins. This rotation creates absolutely captivating spiral patterns.

const rotation = map(y, 0, height, 0, TWO_PI);
rotate(rotation);

The Bounce Effect

The bouncing behavior is handled by a simple condition: when the line reaches a horizontal edge, we reverse its velocity. However, I noticed a small bug in the original code: vertical bouncing isn’t implemented! The line will eventually exit the canvas through the top or bottom.

What’s Missing?

To perfect this animation, we’d need to add the vertical bounce condition:

if(y > height || y < 0) {
  speedY = -speedY;
}

Why It’s Fascinating?

What makes this animation particularly interesting is the balance between control and chaos. The programmer defines simple rules, but the result is complex, organic, and unpredictable. This is the essence of generative art: creating systems that surprise us.

Every time you refresh the page, you get a new piece of art. The patterns that emerge depend on random initial conditions, creating an infinity of possible variations.

Taking It Further

Here are some ideas to experiment with this code:

  • Add multiple simultaneous lines with different velocities
  • Vary the stroke weight over time
  • Use a semi-transparent background to create trailing effects
  • Play with other color blending modes
  • Add mouse interaction

Generative art is an infinite playground. This little piece of code is just a seed that can grow in a thousand different directions.