Search code examples
javafor-loopprocessingrect

This for loop won't draw rectangles, but will write to console


for (int i = 0; i < 50; i++){
        noStroke();
        fill(50,50,50);
        rect(0,0,100,100,i);
        System.out.println(i);
        delay(100);
    }

This is the for loop, it will write the numbers 0 to 50, and then draw a rectangle. The goal is to have it draw rectangles with an increasing radius on the corners. It does not do the rect(), but does do the System.out.println();. This is written in java processing.


Solution

  • Don't use the delay() function to create animations.

    Nothing will draw to the screen until the draw() function finishes (or if you're not using a draw() function, until the code ends). Everything is drawn to an off-screen buffer, and then the buffer is drawn to the screen all at one time when the draw() function finishes.

    So really you're drawing a rectangle to the off-screen buffer, waiting 100 ms, drawing another rectangle to the off-screen buffer, waiting 100 ms, drawing another rectangle, and so on. You won't actually see anything on the screen until after all of that waiting completes.

    If you want to create an animation, don't use a loop. Instead, use the draw() function along with a sketch-level variable that you increment (or just use the predefined frameCount variable).

    Another problem is that you're just drawing the same color rectangle over and over again. You're drawing a gray rectangle, and then a slightly smaller gray rectangle on top of it, and then a slightly smaller rectangle on top of it, and so on. So you'll never actually see the smaller rectangles, since they blend in to the first rectangle you're drawing.

    Run this program to better understand what's going on:

    noStroke();
    fill(50,50,50);
    rect(0,0,100,100,0);
    fill(255, 0, 0);
    rect(0,0,100,100,10);
    fill(0, 255, 0);
    rect(0,0,100,100,20);