p5.js Reference
Table of Contents
Getting Started
p5.js is a website and library for programming in JavaScript.
To use p5.js:
Go to https://editor.p5js.org
In the upper right corner, click Log in
At the bottom, click Login with Google
Log in with your columbusacademy.org student account
To start a new program:
look in the upper left, click File, and choose Save
Give your project a meaningful name
To load an old program:
look in the upper left, click File, and choose Open
Click on the name of your project.
By default, the p5.js editor shows following program:
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
}
The setup function runs once at the beginning of the program. The draw function runs repeatedly.
Anything on a line after // is considered a comment and is ignored by JavaScript. For example:
rect(1, 2, 3, 4); // This rectangle is drawn and this comment is ignored.
// rect(5, 6, 7, 8); This rectangle is not drawn.
createCanvas(width, height);
Should appear exactly once in your program, as the first line in setup.
Example: createCanvas(400, 400); // canvas is 400 pixels wide and 400 pixels tall
frameRate(framesPerSecond);
By default, the draw function runs 60 times every second, but you can change this. Inside the setup function, use the frameRate function to change how often the draw function runs.
Example: frameRate(2); // runs the draw function twice every second
noLoop();
By default, the draw function runs over and over again, but you can tell p5.js to only run the draw function exactly once. Inside the setup function, simply write: noLoop();
Shapes
The top-left corner of the canvas is (0, 0).
line(x1, y1, x2, y2);
Draws a line from (x1, y1) to (x2, y2).
Example: line(200, 100, 200, 300);
rect(cornerx, cornery, width, height);
Draws a rectangle with top-left corner at (cornerx, cornery).
Example: rect(0, 300, 400, 100);
triangle(x1, y1, x2, y2, x3, y3);
Draws a triangle connecting the points at (x1, y1), (x2, y2), and (x3, y3).
Example: triangle(200, 0, 0, 400, 400, 400);
ellipse(centerx, centery, width, height);
Draws an ellipse with center at (centerx, centery).
Example: ellipse(200, 350, 400, 100);
arc(centerx, centery, width, height, startAngle, endAngle);
Draws a sector of an ellipse with center at (centerx, centery), starting from startAngle and ending at endAngle. Angle 0 is to the right of the center (3 o'clock), and angles increase as we move clockwise around the center. By default, angles are specified using radians (instead of degrees) and range from 0 to 2π (instead of 360). For convience, the constant PI is defined to be 3.141592653589793, and the radians function can be used to convert an angle from degrees to radians. Both of the following examples will draw the bottom-right quarter of a circle.
Example: arc(200, 200, 400, 400, 0, PI / 2);
Example: arc(200, 200, 400, 400, radians(0), radians(90));
Hint: To draw the outline of the arc only, use the noFill function.
Draw Any Polygon
You can draw any polygon by using the line command to draw one line at a time. But you won't be able to color it in that way. That's where beginShape, vertex, and endShape come in. Use these commands to draw any polygon point by point. (Vertex is essentially just another name for a point.) The following example draws a 4-sided polygon in the shape of Nevada.
beginShape();
vertex(100, 100);
vertex(200, 100);
vertex(200, 250);
vertex(100, 150);
endShape(CLOSE);
Text
text(message, x, y);
Draws the given message, with the lower-left corner of the first character at (x, y).
Example: text("Hi there!", 100, 300);
Example: text(42, 100, 300);
Example: text(frameCount, 100, 300);
textSize(size);
Sets the size to draw future text.
Example: textSize(24);
textStyle(NORMAL);
textStyle(BOLD);
textStyle(ITALIC);
Sets the style to use for future text.
textFont(fontName);
Sets the font to use for future text.
Example: textFont("Arial"); // sans-serif
Example: textFont("Verdana"); // sans-serif
Example: textFont("Tahoma"); // sans-serif
Example: textFont("Trebuchet MS"); // sans-serif
Example: textFont("Times New Roman"); // serif
Example: textFont("Georgia"); // serif
Example: textFont("Garamond"); // serif
Example: textFont("Courier New"); // monospace
Example: textFont("Brush Script MT"); // cursive
Colors
All color component values range from 0 to 255.
background(red, green, blue);
Fills canvas with given color, with components ranging from 0 to 255.
Example: background(255, 127, 0); // fills screen with orange
Example: background(220); // fills screen with light gray (220, 220, 220)
stroke(red, green, blue);
Sets color for future lines and outlines of future shapes.
Example: stroke(255, 127, 0); // future lines will appear in orange
strokeWeight(weight);
Sets the thickness of future lines and outlines.
Example: strokeWeight(5); // future lines and outlines will be 5 pixels wide
noStroke();
Future shapes will not be outlined, and future lines will not appear.
fill(red, green, blue);
Sets color to fill future shapes.
Example: fill(255, 127, 0); // future shapes will be filled with orange
noFill();
Future shapes will not be filled in.
Properties
frameCount
Returns the total number of times that the draw function has run since the program started.
Example: background(frameCount);
mouseX and mouseY
Returns the current x or y coordinate of the mouse.
Example: background(mouseX);
Math Functions
random(low, high)
Returns a random number from low to high. For example, random(10, 20) might return 10 or 12.3 or 15 or 19.99, etc., but will never return 0 or 9 or 20.5.
Example: background(random(0, 255));
radians(degrees)
Takes in a number of degrees and converts it into a number of radians. For example, radians(360) is equivalent to 2 * PI.
Example: arc(200, 200, 400, 400, radians(0), radians(90));
Images
To use an image in your project:
Find/download an image to use. Adjust the size appropriately.
Look at the line numbers to the left of your code. Just above them, click on the > icon.
Click the + icon to the right of the words Sketch Files and choose Upload file.
Upload your image file. When it finishes uploading, click the X in the upper right corner. You should now see the file name appear in the list of files on the left.
In the list of files, click on sketch.js to return to your code. At the top of your code, declare a global variable to store your image. For example:
var catPicture;If you not have already done so, define a preload function below the variable and above setup. For example:
function preload() {
}In the preload function, add a line to load the image. For example:
catPicture = loadImage("badkitten.png");
The variable name on the left must exactly match the name of the global variable you declared.
The file name in quotes must exactly match the name of the image file you uploaded.In the draw function, add a line to draw the image. For example:
image(catPicture, 100, 100);
Your final code should look something like this:
image(imageVariableName, cornerx, cornery);
Draws imageVariableName with top-left corner at (cornerx, cornery) in its original size.
Example: image(catPicture, 100, 100);
image(imageVariableName, cornerx, cornery, width, height);
Draws imageVariableName with top-left corner at (cornerx, cornery) shrunk/stretched to given width and height.
Example: image(dogImg, 200, 50, 120, 60);
Ifs / Conditions
Example 1: set background to black only when frameCount is less than 100.
if (frameCount < 100)
{
background(0, 0, 0);
}
Example 2: color changes to red when frameCount is 100, 101, 102, ..., 200
if (frameCount >= 100 && frameCount < 200)
{
fill(255, 0, 0);
}
Example 3: color changes to red only when frameCount is 100, 101, 102, ..., 200 (same behavior as example 2)
if (frameCount >= 100)
{
if (frameCount < 200)
{
fill(255, 0, 0);
}
}
Example 4: rectangle and line appear only when mouse is over the right side of the canvas
if (mouseX > 200)
{
rect(250, 50, 100, 300);
line(200, 0, 0, 400);
}
Example 5: rectangle appears only when mouse is pressed
if (mouseIsPressed)
{
rect(50, 50, 300, 300);
}
Example 6: set background to black if any key is being pressed now
if (keyIsPressed)
{
background(0, 0, 0);
}
Example 7: set background to black if the last key pressed was the letter A. (The secret code for A is 65. Find the secret code for any at https://keycode.info.)
if (keyCode == 65)
{
background(0, 0, 0);
}
Example 8: set background to black if the space bar is being pressed right now. (The secret code for the space bar is 32. Find the secret code for any at https://keycode.info.)
if (keyIsPressed && keyCode == 32)
{
background(0, 0, 0);
}
Example 9: set background to black whenever the red component of the color at (x=100, y=200) is greater than 0. (Specifically, get(100, 200) returns the color at this position. The red function takes in that color and returns the red part of that color. You can also use the green function or blue function to get other parts of a color value.)
if ( red( get(100, 200) ) > 0 )
{
background(0, 0, 0);
}
Variables
A variable is a name for a place in memory that stores a value. At the top of your program, use the var command to declare that you intend to use a variable. (The variable exists until your program stops running.) Inside any function, use = to assign a value to that variable.
Example: A square moves across the screen from right to left. As it moves, its x-coordinate decreases. The value of this x-coordinate is stored in the variable squarex.
var squarex; // variable is declared before any functions
function setup() {
createCanvas(400, 400);
squarex = 400; // variable is initialized (given its first value) inside the setup function
}
function draw() {
background(0, 0, 0);
rect(squarex, 200, 50, 50); // variable is used as the x-coordinate of a rectangle
squarex = squarex - 5; // variable is decreased by 5
}