The Coder's Handbook
Drawing Shapes
THE CANVAS
Making The Canvas
When you write a processing program, the first thing you need to do is set the size of the canvas. You must do so in the setup() method. There are two options:
void size(int canvasWidth, int canvasHeight)
Creates a window with the specific height and width
Code:
size(800, 600); // Creates a window that is 800 wide and 600 tall
void fullScreen()
Makes your running program take up the whole screen
Code:
fullScreen(); // Makes your code take up the whole screen
Built-In Variables
Once you have set the width and height of the window, you can access them any time using the variables width and height.
Hard coded values in your code are called magic numbers and are considered a bad practice. Instead of repeating them, use width and height.
println(width + " by " + height); // Prints out 800 by 600
The Coordinate Plane
In Processing, you’ll use a coordinate plane. This works like in your math class:
The x axis is exactly the same
As you move to the right, X gets bigger.However, the y axis is flipped.
As you move down, Y gets bigger.Notice that there are no negative values.
0,0 is in the top left corner of the screen.
SHAPES
Rectangle
void rect(int x, int y, int width, int height)
A rectangle's x and y coordinates refer to its top-left corner
Code:
rect(200, 300, 60, 25) // Rectangle at (200, 300) that is 60 wide and 25 tall
Ellipse
void ellipse(int x, int y, int width, int height)
An ellipse's x and y coordinates refer to its center
Code:
ellipse(150, 150, 25, 25) // Ellipse at (150, 150) that is 25 wide and 25 tall
Lines
void line(int x1, int y1, int x2, int y,2)
Draws a line between two points
Code:
line(90, 80, 150, 200) // Draws a line between (90, 80) and (150, 200)
Triangle
void triangle(int x1, int y1, int x2, int y2, int x3, int y3)
Draws a line between three points
Code:
triangle(90, 80, 10, 20, 75, 80) // Draws a triangle between (90, 80), (10, 20), and (75, 80)
Looking for more shapes? Check out the official reference.
Note: A few of these may only work on the newest version of Processing.
AN EXAMPLE
Putting It All Together
Code:
void setup()
{
size(400,300);
rect(50, 50, 20, 100);
ellipse(200, 100, 50, 50);
triangle(0, 300, 400, 300, 200, 200);
line(50, 250, 350, 50);
}
RESOURCES
Chapter 1 - Pixels
Drawing and Shapes