Example
// Learning Processing
// Daniel Shiffman
// http://www.learningprocessing.com

// Example 6-9: Simple while loop with interactivity

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

void draw() {
  background(0);

  // Start with i as 0
  int i = 0;

  // While i is less than the width of the window
  while (i < width) {
    noStroke();
    // The distance between the current rectangle and the mouse is equal to the absolute value of the difference between i and mouseX.
    float distance = abs(mouseX - i); 
    // That distance is used to fill the color of a rectangle at horizontal location i.
    fill(distance);
    rect(i,0,10,height);
    // Increase i by 10
    i += 10;
  }
}
  • michel

    Hi.
    I’m really enjoying this book and have been able to follow the course so far.
    Now I’m having some troubles understanding this chapter.

    1: In exercise 6-4 I don’t understand why the outcome of #2: \Local count\
    is zero and not 100 as #1.

    2: I just can’t figure out this example. I manage to do the exercise, to rewrite the example with a for loop instead of a while loop but I still doesn’t understand how it works.
    I would really appreciate an explanation of each step. What is happening to fill etc…

    thanks for a fantastic book!

    Michel

  • http://www.learningprocessing.com Daniel Shiffman

    1) Because “count” is declared in draw(), it is reset to 0 every time draw executes, and therefore can never be any other value than 0.

    2) Check out figure 6-7 for the exact inner workings of a “for” loop.

    Good luck!

  • michel

    Thank you Daniel!

    #2 in my question referred to example 6-9 here above but I just managed to figure it out by recreating each step in the loop on paper after your suggestion. :-)

    Michel

  • Margaret

    I was wondering why you get the same results if you pull the background() out of both setup() and draw()?

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

    void draw() {
    int i =0;
    while (i < width) {
    noStroke ();
    float distance = abs (mouseX – i);
    fill(distance);
    rect (i,0,10,height);
    //increase i by 10
    i+= 10;

    }
    }

  • shiffman

    The rectangles cover the entire window in this case so drawing a background underneath is never seen (or not seen).