Changing shape colors in loops

I am currently trying to change the color of my shapes in a loop, I want the color to change a little each time a ellipse is printed, I don’t know why it is not working it just makes the ellipses all the same color, I can not use one loop because it goes over 255.

void setup() {
  size(400,400);
}


 void draw() {
  for (int i = 40; i <= 500; i = i+80 ) {
    for (int j = 20; j <= 255; j = j+30) {
      fill(j,40,40);
    strokeWeight(3);
    ellipse(i,320,30,80);
  }
 }
}
1 Like

If you want to gradually change the colour of your ellipses, do it outside the for loop. All the lines of cod within void draw() get executed one by one, and at the end of draw your window gets visually updated. This means that if you try to change the colour within a for loop, it won’t gradually change (since by the end of the loop j equals 255; this is the value that gets displayed).

Keep in mind that void draw() is a loop itself. Have you considered declaring a global variable of 0, and that at the end of draw() you can increase this value?

you need to remove the for loop on the inside, the ‘j’ loop is running a whole time for every iteration in the ‘i’ for loop (essentially in your code, you are drawing a whole bunch of ellipses at the same spot with different colours and the last ellipse drawn is the one you see… so its always the same colour)

void setup() {
  size(400,400);
}


 void draw() {
  for (int i = 40; i <= 500; i = i+80 ) {
    //for (int j = 20; j <= 255; j = j+30) {
      fill(i,40,40);
      strokeWeight(3);
      ellipse(i,320,30,80);
   // }
 }
}

to keep the intended effect as the j loop you need to make a new variable, this variable will update for every iteration of the ‘i’ loop, as opposed to looping through every value for every iteration of the ‘i’ loop like in your example.

void setup() {
  size(400,400);
}


 void draw() {
  int j = 20;//badabing its not its own loop
  for (int i = 40; i <= 500; i = i+80 ) {
    fill(j,40,40);
    strokeWeight(3);
    ellipse(i,320,30,80);
    j+=30;// do it here instead of using a loop inside a loop.
  }
}
1 Like

this should look same

void setup() {
  size(400, 400);
  strokeWeight(3);
}

void draw() {
  for (int i=0; i<5; i++) {
    fill(20+i*30, 40, 40);
    ellipse(40+i*80, 320, 30, 80);
  }
}

the original double for loop might be needed for making a grid of elements…
? or was that the idea ?

1 Like

Thank you guys, I did not know I could not use 2 loops at the same time!