For Loop

At first, I wrote my for loop like this:

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

function draw() {
  background(220);
  noFill();

  for (let x = 0; x <= width; x += 20) {
    rect(x, 0, 20, height);

    if (mouseX > x && mouseX < x + 20) {
      fill(255, 0, 0);
    } else {
      noFill();
    }
  }
}

But when I tried this, I noticed something strange: when my mouse was over the first column, the second column turned red instead of the first one.

At first, I found that I could make it work by changing the condition to:

if (mouseX > x + 20 && mouseX < x + 40) {
  fill(255, 0, 0);
}

But then I realized that the real problem was not the range of mousex The problem was the order of my code.

In my original code, I drew the rectangle first:

rect(x, 0, 20, height);

and only after that did I check whether the mouse was inside that column and change the fill color. This means the fill color does not affect the rectangle that was just drawn. Instead, it affects the next rectangle in the loop.

So I changed the order:

for (let x = 0; x <= width; x += 20) {
  if (mouseX > x && mouseX < x + 20) {
    fill(255, 0, 0);
  } else {
    noFill();
  }

  rect(x, 0, 20, height);
}

Now the program first checks whether the mouse is inside the current column, decides whether the fill should be red or empty, and then draws the column. This makes the correct column turn red.

I had a similar problem when I tried to do the same thing with a while loop. At first, I wrote:

while (x <= width) {
  rect(x, 0, 20, height);
  x += 20;

  if (mouseX > x && mouseX < x + 20) {
    fill(255, 0, 0);
  } else {
    noFill();
  }
}

This did not work the way I expected either. Later, I moved rect(x, 0, 20, height); x += 20; below the statement, and then it worked.

From this, I realized that the order of the code inside a loop is really important. The computer executes the code from top to bottom. If I want to decide how an object should look before drawing it, I need to check the condition and set its style first, and then draw the object.

self-portrait

for (let x = 0; x <= width; x += 20) { for (let y = 0; y <= height; y += 20) { let d = dist(mouseX, mouseY, x, y); if (d < 150) { fill("white"); space = map(d, 0, 150, 30, 1); } else if (d > 150 && d < 200) { fill(255, 0, 0); space = 7; } else { fill(0); space=10 }