Nested for-loops and grids

Lecture slides

https://slides.com/otso_havanto/programming-for-visual-artists-6/embed

Nested for-loops and noise

Nested noise lines with for-loops example:

function setup() {
  createCanvas(windowWidth, windowHeight);
}

function draw() {
  background(255);

  for (let row = 0; row < height; row += 100) {
    beginShape();
    for (let x = 0; x <= width; x += 10) {
      let offset = noise(x * 0.01, row, frameCount * 0.01);
      let y = row + offset * 100;
      vertex(x, y);
    }
    endShape();
  }
}

Grid with nested for loops

The following sketch illustrates how to iterate through x and y cordinates with nested for-loops.

function setup() {
  createCanvas(windowWidth, windowHeight);
}

function draw() {
  background(255);
  for (let y = 0; y < height; y += 100) {
    for (let x = 0; x < width; x += 100) {
      circle(x, y, 100);
    }
  }
}

The example below iterates trough rows and columns and the coordinates are then calculated based on the current row and column number.

let numElements = 3;

function setup() {
  createCanvas(windowWidth, windowHeight);
  textAlign(CENTER, CENTER);
}

function draw() {
  background(255);
  let cellWidth = width / numElements;
  let cellHeight = height / numElements;

  for (let row = 0; row < numElements; row++) {
    for (let col = 0; col < numElements; col++) {
      let x = col * cellWidth;
      let y = row * cellHeight;
      rect(x, y, cellWidth, cellHeight);
      text(row * numElements + col, x + cellWidth / 2, y + cellHeight / 2);
    }
  }
}

Define custom functions

You can define your own custon functions with the function keyword. You can define what parameters the function takes and use those parameters inside the function. The following example defines a function drawShape that draws a a cluster of rectangles. The function takes four parameters ´posX´, ´posY´, ´numTimes´ and ´offset´. The function is then called inside the draw() function in nested for-loops.

function setup() {
  createCanvas(windowWidth, windowHeight);
}

function draw() {
  background(220);
  for (let y = 0; y < height; y += 100) {
    for (let x = 0; x < width; x += 100) {
      drawShape(x, y, 4, 10);
    }
  }
}

function drawShape(posX, posY, numTimes, offset) {
  for (let i = 0; i < numTimes; i++) {
    let x = posX + offset * i;
    let y = posY + offset * i;
    rect(x, y, 50);
  }
}

Assignment

Option 1:

Create an ornament by repeating shapes in a grid. You can for example do the following:

  1. Draw a shape in a function you defined.
  2. Adjust the function to take x and y coordinates as parameters.
  3. Create a grid with nested for loops and call the function inside the loop.
  4. Add other parameters to your shape function and animate those or adjust them based on the x and y coordinates.

Option 2:

Choose a grid-based artwork from the recode projecct and create either a copy of the work or your own intrepretation of it with p5.

More resources