教程 Get Started

Get Started

By Layla Quiñones, Jaleesa Trapp

Welcome to p5.js! New to p5.js and want to learn some basics for creating an interactive sketch? Follow this tutorial to create a simple interactive landscape. You will learn how to:

  • Change the canvas size and background color
  • Add, customize, and color shapes and text
  • Add simple interactivity by having your sketch respond to the mouse pointer position
  • Comment code
  • Use the p5.js reference pages to learn more

Prerequisites

Before you begin you should be able to:

or 

  • Create and save a new p5.js project in VS Code (or another code editor)

For a step-by-step guide to creating and saving projects in the p5.js Web Editor or VS Code, visit Setting Up Your Environment.

Step 1: Name and save a new p5.js project

  • Create a new p5.js project, give it a name, and save it.

Using the p5.js Web Editor:

  • Log in to the p5.js Web Editor.
  • Name your project “Interactive Landscape” by clicking the pencil icon and typing “Interactive Landscape” into the text box that appears.
  • Click on File and select Save.
  • Confirm your project is saved by navigating to your gallery of saved sketches:
    • Click on File and select Open.
    • Your most recent sketches will appear at the top of the list of projects saved on your account.

A user on the p5.js Web Editor names a new project “Interactive Landscape”, saves it, finds it in their gallery of saved sketches, and clicks the project's name to open it.

A user on the p5.js Web Editor names a new project “Interactive Landscape”, saves it, finds it in their gallery of saved sketches, and clicks the project's name to open it.

Default Code

All p5.js projects include the p5.js library and three files: index.html, style.css, and sketch.js. Make changes on the canvas by adding code to the sketch.js file. New p5.js projects begin with the following code in the sketch.js file:

function setup() {
  createCanvas(400, 400);
}
function draw() {
  background(220);
}

Every sketch.js file begins with two main functions: setup() and draw()

Functions are sequences of instructions that perform specific tasks. 

When the code in sketch.js is executed:

  • setup() is called and runs one time. It can be used to set default values for your project.
    • Within the curly brackets ({}) for setup(), createCanvas(400, 400) creates an HTML canvas that is 400 pixels wide and 400 pixels high that you can see in the preview window. 
  • draw() is called directly after setup() and executes the lines of code inside its curly brackets 60 times per second until the program is stopped or the noLoop() function is called. 
    • Within the curly brackets of draw(), also known as the draw() code block, the background() function sets the color of the canvas background. The default value (220) sets the color of the canvas to gray.

Visit the p5.js reference pages for setup(), draw(), createCanvas(), and background() to learn more.

Step 2: Change the size of the canvas

  • Change the size of the canvas so that it is 600 pixels wide and 400 pixels high by changing the arguments for createCanvas(). Press Play to see changes in the preview window.
  • Make sure you press the Play button or have the Auto-refresh box checked to update the canvas.

Your code should look like this:

function setup() {
  createCanvas(600, 400);
}
function draw() {
  background(220);
}
Tip

Click Play and check the box next to “Auto-refresh” on the p5.js Web Editor to continuously update the canvas as you add more code to your project. With this box checked, you won’t need to press the Play button every time you make changes to your sketch.

Step 3: Use comments to describe code

  • Write a comment that describes what createCanvas(600, 400) does. 

Your code can look like this:

function setup() {
  // Creates a canvas 600 pixels wide
  // and 400 pixels high.
  createCanvas(600, 400);
}
function draw() {
  background(220);
}

Comments

Using comments in your sketches can help you remember the purpose of each line of code. Since JavaScript can’t read comments, they are a great way to communicate your ideas to other people who explore your code, or to remind yourself of what your code is doing.

  • Use two forward slashes anywhere in the sketch ( //comment) to embed single line comments.

Statements

sketch.js files are written in JavaScript, where each line of code is called a statement. Each statement ends with a semicolon (;). It is best practice to add semicolons after every statement you write in the sketch.js file. You SHOULD NOT include a semicolon after curly brackets in functions and if statements.

For more information about comments and statements, watch this video from The Coding Train.

Step 4: Change the background color

  • Change the color of the canvas background to a sky blue color by changing the arguments in the background() function to background(135, 206, 235)
  • Add comments to describe this line of code.
  • Have the Auto-refresh box checked to update the canvas automatically.

Your code can look like this:

background() and other p5.js commands, like shapes, are also functions. The background() function specifically changes the color of the background of the canvas. According to the p5.js reference page for background(), the three arguments seen in the code above represent values for red, green, and blue that correspond to the blue color seen on the canvas.

There are over 10 million combinations of numbers for red, green, and blue that correspond to colors you can use. These are known as RGB color codes. In the code above we see that the value for R is 135, the value for G is 206, and the value for B is 235. This corresponds to the light blue color shown on the canvas. 

Visit the p5.js reference pages for background() and color to learn about more ways you can change the background color of the canvas.

Tip

Use Google’s Color Picker to search for the code that can set the background to any color. Find the color you would like to use, copy the numbers in the box labeled RGB, and paste them into background().

Step 5: Draw shapes on the canvas

  • Draw a sun in the top-right corner of the canvas using the circle() function. 
  • Add a semicolon (;) to end this line of code.
  • Add a comment that describes this line of code.
Note

Be sure to add shapes within the curly brackets (in the code block) of the draw() function, and have the Auto-refresh box checked to update the canvas automatically.

Your code should look like this:

Some shape functions, such as circle(), use numbers that describe the horizontal location (x-coordinate), vertical location (y-coordinate), and size (width and height) of a circle. The x- and y-coordinates indicate the center point (x, y) of the circle (see diagram below).

  • The first argument in the circle() function used in the code example above, the number 550, is the x-coordinate of the center point. This means that the center point is located 550 pixels to the right of the left edge of the canvas.
  • The second argument, the number 50, is the y-coordinate of the center point. This means that the center point is located 50 pixels below the top edge of the canvas.
  • The third argument, the number 100, is the size of the circle (width & height). This means that the circle is 50 pixels wide and 50 pixels high.

A diagram of a circle with a center point at (x,y) and diameter “size”. The syntax for the syntax for using the circle function is displayed above the diagram as: “circle(x, y, size);”

A diagram of a circle with a center point at (x,y) and diameter “size”. The syntax for the syntax for using the circle function is displayed above the diagram as: “circle(x, y, size);”

Visit the p5.js reference page for circle() to learn more.

p5.js Canvas Coordinates

The canvas comes with an invisible coordinate system that begins at a horizontal location of 0 and vertical location of 0 in the top-left corner. 

A diagram of a HTML <canvas> element shows a grid pattern overlay with the horizontal axis representing x-coordinates, the vertical axis representing y-coordinates, and each intersection of the grid representing specific (x,y) coordinate pairs. An arrow along the x-axis shows that x-coordinates increase as they move to right on the canvas. An arrow along the y-axis shows that y-coordinates increase as they move down on the canvas.

A diagram of a HTML <canvas> element shows a grid pattern overlay with the horizontal axis representing x-coordinates, the vertical axis representing y-coordinates, and each intersection of the grid representing specific (x,y) coordinate pairs. An arrow along the x-axis shows that x-coordinates increase as they move to right on the canvas. An arrow along the y-axis shows that y-coordinates increase as they move down on the canvas.

As an object on the canvas moves to the right of this point, its horizontal location increases. As an object on the canvas moves down from this point, its vertical location increases. As an object moves to the left on the canvas, its x-coordinate decreases; as an object moves up on the canvas, its y-coordinate decreases. The following examples display values for the x- or y-coordinates of a circle as its position changes on the canvas:

  • This example displays the x-coordinate of a circle as it moves horizontally on the canvas.
  • This example displays the y-coordinate of a circle as it moves vertically on the canvas.

The maximum values for the horizontal and vertical position of the canvas are set by the createCanvas() function. The first number in createCanvas() is the x-coordinate of the right edge, and the second number is the y-coordinate of the bottom edge. 

Learn more about the HTML canvas coordinate system and shapes on this p5.js reference page

Step 6: Color shapes and outlines on the canvas

  • Color the sun by adding fill("yellow") on the line above circle().
  • Color the outline of the sun by adding stroke("orange")on the line above circle().
  • Change the thickness of the outline by adding strokeWeight(20)on the line above circle().
  • Add comments to describe the code.
Note

Be sure to add fill(), stroke(), and strokeWeight() within draw()’s code block, on the lines BEFORE a shape is drawn. 

Your code should look like this:

The fill() function sets the color for any shape on the canvas, and the stroke() function sets the color for lines and outlines. They both use the same arguments that background() uses. The code above uses an HTML color name as the arguments for fill() and stroke(); we can also use RGB and HEX color codes. The strokeWeight() function uses a number to set the thickness for lines, outlines, and points that are below it; the default strokeWeight() is 1 pixel. In the code above, strokeWeight(20) sets the circle’s outline to 20 pixels.

Tip

In the p5.js Web Editor, you can search for different colors to use in fill(), stroke(), and background() by clicking on the small colored box next to the color’s name! Type an HTML color name as an argument, and the box will appear. Color names are string data types and are therefore surrounded by quotation marks ("").

After coloring a circle yellow using fill(“yellow”), a user coding in the p5.js Web Editor clicks on the yellow square that appears next to the HTML color “yellow”. This reveals the color tool which is used to select a  red color. The user then clicks the code editor causing the color of the circle to change from yellow to red.

After coloring a circle yellow using fill(“yellow”), a user coding in the p5.js Web Editor clicks on the yellow square that appears next to the HTML color “yellow”. This reveals the color tool which is used to select a red color. The user then clicks the code editor causing the color of the circle to change from yellow to red.

Fill Order

The default value for fill() is white. This means that if fill() never appears in draw(), all shapes will be white by default. To change the color of any shape on the canvas, you must call fill() before drawing the shape. The default value for stroke() is black. To change the color and shape of the outline, stroke() and strokeWeight() must be called before the shape is drawn. When drawing multiple shapes on the canvas, call fill(), stroke(), and strokeWeight() each time the color of a shape or outline changes. 

Visit the color reference page to learn more about fill(),stroke(), and strokeWeight(). Use the p5.js Web Editor’s color tool or Google’s Color Picker to search for color codes to use in fill(), stroke(), and background().

Step 7: Draw and color more shapes on your canvas

  • Draw grass on the bottom half of the canvas:
    • Reset the values for the outline of shapes by adding stroke(0) and strokeWeight(1) below the code for the sun.
    • Add a rectangle shape to your canvas using rect(0, 200, 600, 200).
    • Add fill("green") on the line above the rectangle statement to color the rectangle green.
    • Add a comment that describes the lines of code that create the grass.
  • (Optional) Add more details to your landscape using shapes and colors. Click on the shape functions below to learn how to include them in your sketch:
Note
  • Be sure to add shapes and colors within the curly brackets of the draw()function.
  • fill() should be called on the line BEFORE the line a shape is drawn on to color that specific shape. fill() must be called again to change the color of additional shapes.

rect() uses numbers that describe the horizontal location (x-coordinate), vertical location (y-coordinate), width and height of a rectangle. The x- and y-coordinates (x, y) indicate the top left point of the rectangle (see the diagram below).

  • The first argument in the rect() function used in the code example above, the number 0, is the x-coordinate. This means that the top left corner of the rectangle is on the left edge of the canvas.
  • The second argument, the number 200, is the y-coordinate. This means that the top left corner of the rectangle is 200 pixels below the top edge of the canvas.
  • The third argument, the number 600, is the width of the rectangle. This means that the rectangle is 600 pixels wide.
  • The fourth argument, the number 200, is the height of the rectangle. This means that the rectangle is 200 pixels tall.

A diagram of a rectangle with a horizontal length labeled “width”, vertical length labeled “height”, and a point  in the top left corner labeled “(x,y)”. The syntax for using the rect() function is displayed above the diagram as: “rect(x, y, width, height);”

A diagram of a rectangle with a horizontal length labeled “width”, vertical length labeled “height”, and a point in the top left corner labeled “(x,y)”. The syntax for using the rect() function is displayed above the diagram as: “rect(x, y, width, height);”

Visit the p5.js reference pages for rect(), simple shapes, and color to learn more.

Step 8: Add emojis

  • Add a flower emoji and a ladybug emoji (or any other emojis you like) to your landscape: 
    • Draw a flower on the canvas using text("🌸", 100, 250);
    • Draw a ladybug on the canvas using text("🐞", 300, 250);
    • Adjust the size of the flower and ladybug using textSize(75)on the line before the emojis are drawn.
    • Add comments that describe the lines of code that create the flower and ladybug.
    • Make sure you press the Play button or have the Auto-refresh box checked to update the canvas.
Note

Be sure to add textSize() and text() within the draw()’s code block AFTER the lines of code that draw the grass. If text() appears before rect() in the code, and is placed where the rectangle is drawn on the canvas, there is a chance that the text will be hidden behind the rectangle! See the Drawing Order section below for more explanation on how overlap can happen.

Your code should look like this:

text() uses a string, which is any text within quotation marks (""), and numbers that describe the x-coordinate and y-coordinate of the text. The x- and y-coordinates (x, y) indicate the bottom-left point of the text box (see the diagram below).

  • The first argument in the text() function used in the code example above, the string "🌸", is the text that will appear on the canvas. All strings used in p5.js must be within quotation marks ("").
  • The second argument, the number 100, is the x-coordinate. This means that the bottom-left corner of the text box is 100 pixels to the right of the left edge of the canvas.
  • The third argument, the number 250, is the y-coordinate. This means that the bottom-left corner of the text box is 250 pixels below the top edge of the canvas.

A diagram with the word “string” inside a rectangle outlined by dashed lines, and a point in the bottom left corner labeled “(x,y)”. The dashed outline represents the invisible box that encloses the text, and the point “(x,y)” represents the coordinates that describe its location on the HTML <canvas>.

A diagram with the word “string” inside a rectangle outlined by dashed lines, and a point in the bottom left corner labeled “(x,y)”. The dashed outline represents the invisible box that encloses the text, and the point “(x,y)” represents the coordinates that describe its location on the HTML <canvas>.

textSize() uses a number to describe the size, in pixels, for any text() function that appears after it is called. Be sure to use textSize() before you call the text() function if you wish to change the size of the text that appears on the canvas. 

Drawing Order

Since draw() executes the code within the brackets over and over again, shapes are drawn on the canvas like layers. Code that appears first will be drawn first, and code that appears further down in draw() will be drawn after. This is why we must set fill(), stroke(), and textSize() before we add shapes or text to the canvas. p5.js needs to know the color or size of shapes and text before they are drawn. This also allows for overlapping shapes and can sometimes hide shapes behind others! Be sure to check the x- and y-coordinates of your shapes to see if they are behind other shapes.  

See these sketches for examples of layering: overlapping shapes (hidden) and overlapping shapes

Visit the reference pages for text(),textSize(), and draw() to learn more.

Data Types

Some functions in p5.js need arguments that are string data types, while other functions need arguments that are number data types.

  • Strings: represented by text and always surrounded by quotation marks ("")
  • Numbers: represented by a number 

For example:

Step 9: Make it interactive!

  • Change the x- and y-coordinate for the ladybug emoji to mouseX, mouseY.
    • text("🐞", mouseX, mouseY);
  • Move your mouse pointer across the canvas and see how the ladybug follows your mouse pointer location!
    • Make sure you press the Play button or have the Auto-refresh box checked to update the canvas.
  • Add comments to describe how the ladybug can move with the mouse pointer.

Your code should look like this:

mouseX and mouseY are built-in variables that come with the p5.js library – they are referred to as system variables. Variables store values in them that can be used later in a sketch. They are also helpful to use when you know the value of something, such as x- and y-coordinates, is changing. mouseX and mouseY specifically store the x- and y-coordinates of the mouse pointer as it is dragged over the canvas. You can use mouseX and mouseY as any argument that requires a number

See some of these examples of how you can use mouseX and mouseY in a sketch:

Visit the p5.js reference pages for mouseX and mouseY to learn more! Be sure to review the p5.js coordinate system by visiting the p5.js reference page for the canvas coordinate system and shapes. Explore other system variables included in the p5.js reference:

  • width: The width of the canvas
  • height: The height of the canvas
  • pmouseX: The previous x-coordinate of the mouse
  • pmouseY:The previous y-coordinate of the mouse

Errors

It is easy to spell function names wrong or forget a comma. Syntax rules help the computer interpret code. When a “rule” is broken, an error message will appear in the console (for example, if circle() is spelled wrong). These errors are commonly referred to as “bugs.” The console displays messages from the editor with details about any mistakes you might have made. When your code does not execute correctly, there might be a bug in your code! Visit the Field Guide to Debugging for examples of common errors and how to fix them.

For more information, watch this video from The Coding Train.

Next steps

Previous step

Resources


相关参考


相关示例