This was one of the most puzzling things to me when I started off with Processing. Luckily, John helped me out with understanding how the draw() function works. Thanks again John
Okay, first things first....
You know that the draw() function keeps looping continuously.
Now, whatever code you put into the draw function, will not be displayed on the screen until the draw function loops.
So, within the draw function if you have code like -
.....
void draw()
{
for(int i=0;i<255;i++)
{
fill(i);stroke(i);rect(0,0,100,100);
}
}
What happens is that the entire for loop is executed, and every rectangle is actually drawn on....maybe a graphics buffer....and the final result of all superimposed images is displayed on the screen when draw() completes its loop.
So for the above code, all you'll see on the screen is a white rectangle.
Even if you place a delay(1000); within the for loop,
void draw()
{
for(int i=0;i<255;i++)
{
delay(1000);
fill(i);stroke(i);rect(0,0,100,100);
}
}
you won't see the 254 rectangles being displayed in different shades coz these rectangles are being drawn in the graphics buffer, and not on the screen. Instead, what will happen is, the delay will be executed 255 times, and you'll have to wait for 255*1 seconds till the for loop completes and all the rectangles to be drawn one over the other in the graphics buffer.
When the for loop is completed, and control reaches the end of the draw() function, whatever has happened in the graphics buffer will be displayed on the monitor.
This functionality works beautifully when you want to superimpose images over one another. You'll love it
So, if you want to see each rectangle being displayed one by one, you'll have to do something like this...
int i=0;
void draw()
{
stroke(i);fill(i);rect(0,0,100,100);
delay(50);
if (i==255) i=0; else i++;
}
Hope you understood how it works.....I'm sure you'll be able to apply the logic to your program.
Cheers!! and all the best with your further programming