Processing Tips


setup() and draw() methods

Most Processing sketches start with setup() and draw() methods. These methods are like the main method in a Java program, they tell the computer what code to run when you hit the play button! The setup() method is run once at the beginning of your program. The draw() method is called over and over again until you stop your program. In your code, these methods should look like this:


    void setup(){
       

    }

    void draw(){


    }
                            

size

The next step is often to make the sketch large enough that you can put things inside of it. To do this, use the size method.

size( width, height)

Sets the size of your sketch.


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

    }

    void draw(){


    }
                            

shapes

Since Processing is a graphically-oriented programming language, drawing shapes is something you will likely do in every sketch. Here are a few of the most common shapes:

ellipse( x, y, width, height)

An ellipse is an oval shape. When the width and height of an ellipse are equal, it makes a circle.

rect( x, y, width, height)

Draws a rectangular shape. Has the same four parameters as an ellipse.

triangle( x1, y1, x2, y2, x3, y3)

Draws a triangular shape. Takes three pairs of coordinates and draws lines between them.


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

    }

    void draw(){
        ellipse(25, 50, 100, 100);

    }
                            

colors

Time to make things pretty!

fill( redValue, greenValue, blueValue)

Changes the color of your shape. The color will be applied to every shape until it is set to something else. You should change the color of your shape on the line before you draw it!

background( redValue, greenValue, blueValue)

Changes the background color of the entire sketch.


    void setup(){
        size(400,600);
        background(0,255,0);
    }

    void draw(){
        fill(255,0,0);
        ellipse(25, 50, 100, 100);
    }
                            

built-in variables

Here are some very useful variables that come free with Processing!

mousePressed

Its value is "true" when the mouse is pressed. Often used inside of an if statement.

mouseX

Contains the current x-position of the mouse.

mouseY

Contains the current y-position of the mouse.

width

Contains the width of the sketch.

height

Contains the height of the sketch.


    void setup(){
        size(400,600);
        background(0,255,0);
    }

    void draw(){
        if(mousePressed){               //if the mouse is pressed 
            fill(255,0,0);                  //fill red 
        }
        else{                           //else
            fill(0,0,255);                  //fill green
        }
        ellipse(mouseX, mouseY, 100, 100);  //using these variables makes this shape follow the mouse
    }