Creating a Picture with Variables and Shape Drawing Functions
In this chapter, we will use the various functions provided in p5.js to draw shapes. It includes an explanation of the coordinate system we will use and what parameters each shape has. You will also learn about variables and calculations and be able to easily create a regular arrangement of shapes.
The Coordinate System
On our computer monitors, we usually see a grid of tiny dots called pixels, each of which changes color to display a picture.
In addition to the physical monitor structure, the drawing area (canvas) in p5.js has a similar structure, and you can create a canvas of any size with createCanvas(horizontal pixels, vertical pixels)
.
The coordinates on the canvas are the positions of the pixels themselves. The x- and y-coordinates have their origin (0, 0) at the pixel in the top left corner of the monitor, with the x-axis extending to the right and the y-axis extending downward. Note that the direction of the y-axis is different from the coordinate system we often use in mathematics. You will need to tell the computer many coordinates when you draw figures from now on, so get used to it as you use it.
Functions to draw shapes
Here are many functions to draw a shape. It is tough to learn them all now, so please read only those that you are likely to use. If you have any questions later, you can always come back to this chapter. Rather than trying to remember all of the explanations, try rewriting the numbers you enter in each of the sample codes and observe how they change. It will lead you to an understanding of the coordinates we use.
Draw a point
.
point
can draw a point by painting a single pixel.
It may be difficult to see on your screen, so please zoom in your browser.
Draw a line
Draw a line by specifying the x and y coordinates of the starting point and the end point.
function setup() {
createCanvas(500, 500);
background(200);
}
function draw() {
line(50, 50, 450, 250);
}
Draw a rectangle with rect
The argument passed is rect(top-left x-coordinate, top-left y-coordinate, width, height)
by default.
function setup() {
createCanvas(500, 500);
background(200);
}
function draw() {
rect(100, 100, 300, 200);
}
You can change the way coordinates are specified by calling rectMode
before rect
.
The default method is rectMode(CORNER)
.
Draw a rectangle with center and size
You can specify rectMode(CENTER)
to draw a rectangle with a specified center and horizontal and vertical sizes.
rect(x-coordinate of center, y-coordinate of center, width, height)
function setup() {
createCanvas(500, 500);
background(200);
}
function draw() {
rectMode(CENTER);
rect(250, 250, 300, 200);
}
Draw a Rectangle with Both Edges
Using rectMode(CORNERS)
, you can draw a rectangle with the coordinates of the upper left corner and the lower right corner.
rect(top-left x-coordinate, top-left y-coordinate, bottom-right x-coordinate, bottom-right y-coordinate)
function setup() {
createCanvas(500, 500);
background(200);
}
function draw() {
rectMode(CORNERS);
rect(100, 100, 300, 200);
}
Draw a ellipse
Draw an ellipse by specifying the center position and vertical and horizontal diameters.
function setup() {
createCanvas(500, 500);
background(200);
}
function draw() {
ellipse(250, 250, 150, 100);
}
By writing ellipseMode(RADIUS)
before ellipse
, you can specify the size of the ellipse by its radius.
function setup() {
createCanvas(500, 500);
background(200);
}
function draw() {
ellipseMode(RADIUS);
ellipse(250, 250, 150, 100);
}
For circles, use circle
.
As with ellipse
, you must give the center position and diameter.
You can also change it to specify the radius by preceding it with ellipseMode(RADIUS)
.
function setup() {
createCanvas(500, 500);
background(200);
}
function draw() {
circle(250, 250, 100);
}
Draw a triangle
Draw a triangle given the three vertex coordinates.
function setup() {
createCanvas(500, 500);
background(200);
}
function draw() {
triangle(50, 450, 250, 50, 450, 450 );
}
Variables and Calculations
One of the advantages of drawing with programs is that you can call functions with the results of calculations using variables. Variables can be regarded as the same as variables used in mathematics. Once you have written the formula for determining the coordinates, you can display the figure on the screen without having to give the coordinates as a concrete number. The following is an example of how to compute the coordinates of a figure. This program draws three circles, shifting them by 150 to the right.
function setup() {
createCanvas(500, 500);
background(200);
}
function draw() {
let x;
let y = 250;
let width = 100;
x = 100;
circle(x, y, width);
x = x + 150;
circle(x, y, width);
x = x + 150;
circle(x, y, width);
}
Three variables, x
, y
, and width
, appear in Example 2-2-1.
In programming, variables do not have to be named with a single letter, as in mathematics, but can be named as you like.
You can write programs that are readable and easy to understand by using meaningful words such as width
.
The important thing is to know the meaning of the variable, so always think about what kind of name you should give it.
Before we go into detail about how to use variables, let's look at some calculations in action.
The following is a program that simply performs a calculation with a = 7
and b = 4
.
You can have it compute the arithmetic operations and other operations on variables and numbers in the general writing style of a computer.
Note that %
is a remainder calculation.
In addition to the arithmetic operations, other useful functions, like trigonometric functions, are provided.
In the example, PI
is used to compute sin, cos
.
These functions often use values in radians as angles.
The radians(degrees)
function can be used to convert from the arc-degree system (°).
Other functions can be found at reference/#math.
[Example 2-2-2. Calculation using variables]
function setup() {
let a = 7;
let b = 4;
let sum = a + b; // 11
let diff = a - b; // 3
let prod = a * b; // 28
let quot = a / b; // 1.75
let rem = a % b; // 3
let sine = sin(PI/2); // sin(π/2) == 1
let cosine = cos(radians(180)); // cos(180°) = cos(π) = 1
print(sum);
print(diff);
print(prod);
print(quot);
print(rem);
print(sine);
print(cosine);
}
function draw() {
}
Using Variables
Here is a detailed syntax explanation.
We tell the computer which variables we want to use by writing let <variable name>
, which is called a declaration of a variable.
The variable we have declared can then be used freely under that name.
Caution Although it is possible to declare the same variable name in some cases, it may overwrite the variable and cause the program not to work as expected. This is not covered in class, as there are some complicated rules about this. For now, it is okay as long as you keep in mind not to use the same variable names. If you are interested, please read Lifetime of Variables in the Appendix.
Use =
sign to assign a value to a variable.
The value you write on the right side of =
will be assigned to the left side.
Variables can be declared and assigned at once, so the following two codes are equivalent.
// Declare and assign variables separately
let x;
x = 10;
// Declare and assign variables at once
let x = 10;
You can assign the result of an operation or function to a variable.
Unlike the mathematical equal sign, the operation of assignment is oriented. For example, the following writing is not allowed
In addition, in your program you can write like this
In mathematics, this is an impossible expression, but in programming, it means to add 150 to the original value ofx
and assign it to x
again.
In other words, this statement is an operation to increase x
by 150.
In Example 2-2-1, this statement is used in a situation where you want to shift the position of the circle to the right.
Using Variables to Create Animations
In p5.js, the draw
block is called repeatedly to achieve animation. (Mechanism for animation)
You can prepare variables to be used throughout the animation and control the movement by changing the values little by little.
The following program uses the variable angle
to represent the angle of the circle's coordinates, and draws it by incrementing it by 0.1 radians per frame to create a circular motion.
let angle = 0; // Set angle = 0 at the beginning.
function setup() {
createCanvas(500, 500);
background(200);
}
function draw() {
background(200);
angle = angle + 0.1; // increase angle by 0.1
let center_x = 250;
let center_y = 250;
let r = 100;
let x = center_x + r*cos(angle);
let y = center_y + r*sin(angle);
circle(x, y, 60);
}
As in this example, variables you want to use across frames must be declared outside any block.
Conversely, a variable declared inside a block, even if it has the same name, is a different variable created for each execution draw
, and cannot inherit information from the previous frame.
// *angle is reset to 0, so the shape does not move.
function draw(){
let angle = 0;
angle = angle + 0.1;
...
}
When the Picture You Want doesn't Appear
A program only works as written.
If your program does not work as you expect, it means that you are calling a function with different arguments than you expect.
In such a case, first use print(<variable>)
at various places in the program to display the value on the console and check what values are passed to the function.
Exercises
Exercise 1
Let's draw a picture of a face using the drawing function. You can use a combination of ellipses, rectangles, and straight lines.
Exercise 2
Draw a picture like the one below. Use mathematical operations to determine how the position and size of the figure can be varied. You do not need to reproduce the colors of the shapes since you have not yet learned about them.
Exercise 3
The following program draws a circle at the position of the variable x, y
.
let x = 100;
let y = 100;
function setup() {
createCanvas(windowWidth, windowHeight);
background(200);
}
function draw() {
circle(x, y, 60);
}
Based on this, write a program that updates x, y
in draw
so that the circle gradually moves from top left to bottom right.
There is no need to loop.
It is OK if the circle disappears off the screen.