Skip to content
On this page

Loops

Loops are essential constructs in generative art, allowing you to repeat actions and create intricate patterns and designs with ease.

Art Editor

In this tutorial we will use the https://editor.p5js.org

It's a free online p5js editor that will work to render almost every code you can make.

Preview

Using Loops

In p5.js, loops can be implemented using constructs like for loops and while loops. These loops iterate over a block of code multiple times, executing it with different parameters or conditions.

The for Loop

The for loop is commonly used when you know exactly how many times you want to repeat an action.

javascript
for (let i = 0; i < 10; i++) {
  // Code to be repeated goes here
  console.log(i);
}
Preview

In this example, the loop will iterate 10 times, with i starting at 0 and incrementing by 1 each time until it reaches 9.

The while Loop

The while loop is used when you want to repeat an action until a certain condition is met.

js
let i = 0;
while (i < 10) {
  // Code to be repeated goes here
  console.log(i);
  i++;
}
Preview

This loop will continue to execute the code block as long as the condition i < 10 is true, incrementing i with each iteration.

Looping Through Arrays

Loops are often used to iterate through arrays and perform actions on each element.

js
let colors = ["red", "green", "blue"];
for (let i = 0; i < colors.length; i++) {
  console.log(colors[i]);
}
Preview

This loop will iterate over each element of the colors array, printing each color to the console.

Integrating Loops with Generative Art

Loops can be combined with randomness to create dynamic and complex generative art pieces. For example, you can use loops to draw patterns, shapes, or animations with varying sizes, positions, and colors.

Example: Drawing Circles with a for Loop

js
function setup() {
  createCanvas(500, 500);
  background(220);

  for (let i = 0; i < 25; i++) {
    let x = random(width);
    let y = random(height);
    let diameter = random(25, 100);
    
    fill(random(255), random(255), random(255));
    ellipse(x, y, diameter);
  }
}
Preview

In this example, a for loop is used to draw 10 circles with random positions, sizes, and colors.

Example: Grid of Random Rectangles

javascript
function setup() {
  createCanvas(500, 500);
  background(220);

  let rows = 5;
  let cols = 5;
  let rectSize = 100;

  for (let i = 0; i < rows; i++) {
    for (let j = 0; j < cols; j++) {
      let x = j * rectSize;
      let y = i * rectSize;
      let rectWidth = random(60, 100);
      let rectHeight = random(60, 100);

      fill(random(255), random(255), random(255));
      rect(x, y, rectWidth, rectHeight);
    }
  }
}
Preview

In this example, a grid of random rectangles is generated. The for loop is used to iterate over rows and columns, and for each cell in the grid, a rectangle is drawn with random width, height, and color.

Released under the WTF License.