For Loops

Now you know how to write code using functions, variables, and if statements. So far your code has worked by executing each line one after the other: if you want to draw three circles, you’d have to write three separate calls to the circle function.


This is a companion discussion topic for the original entry at https://happycoding.io/tutorials/p5js/for-loops

Nested for loop’s explanation was awesome.:star_struck:
Learnt a lot while coding the horizontal gradient
:hot_face::sunglasses:.

1 Like

I used nested for loop and stroke() and rect() for giving a random color to each pixel on the canvas.
random colored pixels
A canvas with larger no of pixels(around 1e5) was having trouble with higher frameRates. It also made the Preview and the editor laggy.
Is there a better and more efficient ways to do this?

If you’re looking to improve performance, you might look into the set() function. This is a little faster for me than calling the rect() function:

function setup() {
  createCanvas(400, 400);
  frameRate(10);
}

function draw() {
  background(220);
  for(let i=0;i<width;i++){
    for(let j=0;j<height;j++){
      const randomColor = color(random(0,255),random(0,255),random(0,255));
      set(i,j, randomColor);
    }
  }
  updatePixels();
}

And if you really want to speed it way up, you can modify the underlying pixels array directly. This is a little more complicated, but a lot faster.

function setup() {
  createCanvas(400, 400);
  frameRate(10);
}

function draw() {
  background(220);
  loadPixels();
  for (let i = 0; i < width; i++) {
    for (let j = 0; j < height; j++) {
      setColor(i, j, random(0, 255), random(0, 255), random(0, 255));
    }
  }
  updatePixels();
}

function setColor(x, y, r, g, b) {
  let d = pixelDensity();
  for (let i = 0; i < d; i++) {
    for (let j = 0; j < d; j++) {
      index = 4 * ((y * d + j) * width * d + (x * d + i));
      pixels[index] = r;
      pixels[index + 1] = g;
      pixels[index + 2] = b;
      pixels[index + 3] = 255;
    }
  }
}
1 Like

Got exactly what I needed. Thank you.

A great explanation by The Coding Train RELATED to second method ( i.e. the pixels array one), in case if someone else need help too. However, he uses pixelDensity(1) in the video, which makes things a bit simpler but it is a deprecated method.

1 Like