Setup and Draw

Setup and Draw

So far, we have just been writing code without placing that code into any methods.  This is a great way for us to get started but in order to move forward we need to take the next step.

Processing has two special methods that we can define in our sketches.

Setup()
The setup method is run once, at the beginning of the execution of any processing sketch. It is typically used to set things like background, size and other static items.

        void setup()
        {
            // YOUR CODE IS RUN ONCE
        }

Draw()
The draw method is executed in a loop. It is run continuously throughout the execution of the processing applet.

        void draw()
        {
            // YOUR CODE IS RUN OVER AND OVER AGAIN
        }

Here is a common use of setup():

        int myint = 0;  // Notice this is outside of setup().  You can declare and assign variables outside of setup but you can not call methods or issue other commands outside of a method.

        void setup()
        {
            size(500,500);
            background(255,255,255);
            frameRate(15);  // Defines how many times per second draw() will run
            fill(255,0,0);
            stroke(0,0,0);
            strokeWeight(10);
        }

Here is a simple draw() which includes some variable usage (see the int myint = 0 line above):

        void draw()
        {
            rect(myint,myint,50,50);  
            myint = myint + 1;
        }

If we copy these lines of code into Processing we will see a rectangle move from the top left of the screen down to the bottom right. The obvious analogy here is that of animation. The setup function sets up our window and the draw function runs every 15 seconds and gives us the appearance of movement.