Articles

What is a p5.js Script? Complete Setup Guide

Learn what a p5.js script is, how it works, its different types, and how to set up your first project locally in this beginner-friendly guide.

What is a p5.js script?

A p5.js script is a block of JavaScript code written using the p5.js library, designed to create interactive visuals, animations, and creative projects directly in the web browser. At its core, a p5.js script defines how shapes, colors, media, and user interactions behave on a digital canvas using simple, beginner-friendly syntax.

Each script typically contains two essential functions:

  • setup(): Which runs once to initialize your canvas and settings
  • draw(): Which continuously executes to render frames, making real-time graphics and animations possible.

Whether it’s a generative art piece, an interactive game, or a data visualization, a p5.js script is the engine behind the scenes, instructing the browser how to bring your creative ideas to life.

Now that you know what a p5.js script is, let’s take a closer look at how it runs in the browser

Related Course

Learn p5.js

Create generative visualizations and interactive experiences with p5.js, a popular JavaScript library for creative coding.Try it for free

How p5.js scripts work

A basic p5.js project typically involves two main files: a JavaScript file that contains the creative logic (sketch.js), and an HTML file (index.html) that loads both the p5.js library and your custom script into the browser. Let’s break down how each of these files works and what they contain.

JavaScript file (sketch.js)

The core of any p5.js project lies in the JavaScript file. This is where you define how your sketch behaves, what it draws, how it animates, and how it reacts to user input. Every p5.js script revolves around two key functions:

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

The setup() function:

This function runs once at the start of the program. It’s typically used to initialize the canvas, set up variables, or load media assets. In the code here, createCanvas(400, 400) creates a 400×400 pixel canvas in the browser.

The draw() function:

This function runs repeatedly, usually 60 times per second, to update the canvas. Think of it as your sketch’s animation loop. Here, background(220) redraws a light gray background on each frame, giving you a clean slate for each update.

p5.js abstracts the complex canvas API with functions like ellipse(), fill(), and text() for drawing and visuals. It also includes built-in event functions such as mousePressed(), keyPressed(), and windowResized() for handling user input and interaction. This makes it easy to create dynamic, responsive sketches with minimal code.

HTML file (index.html)

The HTML file sets up the structure of the web page and links to the necessary JavaScript resources. For a local p5.js project, your index.html will look like this:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>My p5.js Sketch</title>
<script src="p5.js"></script> <!-- Loads the p5.js library -->
</head>
<body>
<script src="sketch.js"></script> <!-- Loads your custom script -->
</body>
</html>

Here:

  • The <script src="p5.js"> tag in the <head> loads the p5.js library, which provides all the built-in functions like createCanvas(), ellipse(), and mousePressed().

  • The <script src="sketch.js"> tag in the <body> loads your custom code after the library is ready, ensuring everything runs smoothly.

Together, these two files form the complete environment needed to build and run p5.js projects in your browser.

Types of p5.js scripts

p5.js scripts can be categorized based on their purpose, such as drawing, interaction, data handling, or by their structure, from basic loops to object-oriented design. Let us understand these types.

Drawing and visual design scripts

These scripts focus on rendering visuals using p5.js’s simplified drawing tools:

  • 2D Shape Drawing: Use built-in functions like ellipse(), rect(), line(), triangle(), and arc() to create geometric designs.

  • Styling and Color: Control the look of your drawings using fill(), stroke(), strokeWeight(), background(), noFill(), and noStroke().

  • 3D Drawing: Enable WEBGL mode in createCanvas() to use 3D functions like box(), sphere(), cone(), and cylinder(). You can even load 3D models with model().

  • Curves and Paths: Create smooth, flowing shapes using bezier(), curve(), and vertex() functions.

Animation and interaction scripts

These scripts bring movement and user interactivity to your sketches.

  • Animation Loops: Use the draw() function to create real-time animations. Use frameCount and deltaTime for frame control.

  • User Input: Capture mouse and keyboard events with mousePressed(), mouseDragged(), keyPressed(), keyReleased(), and mouseMoved().

  • Interactive Logic: Add interactivity like object tracking, hover effects, and game-like logic using variables and conditionals.

Media and data scripts

These scripts handle external media files and dynamic data.

  • Image Loading and Display: Use loadImage() and image() to render static or animated images in your sketch.

  • Pixel Manipulation: Access and edit individual pixels using get(), set(), loadPixels(), and updatePixels() for effects like filters or glitch art.

  • Data Visualization: Visualize data from files or APIs using shapes, bars, or custom graphs. Read data using loadJSON(), loadStrings(), or loadTable().

Now that you’re familiar with the kinds of projects you can create, let’s walk through how to set up your very first p5.js script locally on your computer.

Setting up your first p5.js script locally

Step 1. Setting up your code editor

Before getting into creating files for your local p5.js project, make sure you have a code editor set up on your computer. If you haven’t used a code editor before, take a look at the Sublime Text Editor article, which goes over the process of choosing and setting up a code editor.

A typical p5.js project consists of index.html for the web page content, including the <canvas> HTML element, style.css for styling the web page, and sketch.js for the JavaScript code for your p5.js sketch.

Create a folder to contain the files for your p5.js project. Inside the folder, create index.html, style.css, and sketch.js files. You can create these files by opening your code editor, creating a new file, and saving it as the name of each of the three files, with the right extensions. In the image below, we’ve created a folder called my_p5_project and the required files inside the folder.

file_view

Step 3. Downloading the p5.js Library

To start programming a local p5.js project, the p5.js library files need to be downloaded and added to the folder you created in the last step. There are a few different ways to do this.

The first method is to download the complete library from the p5.js website. This download includes the p5.js library file, the p5.sound library add-on file, and an example project.

image of complete download

Another method is to download a single library file. There are two types of files available: p5.js and p5.min.js. The main difference between these two files is that p5.min.js is a compressed version of the p5.js file, meaning it is much smaller in size, which enhances load speed when the project is deployed on the web.

image of single file download

After downloading the preferred file, your directory should now look something like this:

p5.js project directory with all files

Alternatively to downloading the library file, you can link to a p5.js file hosted online at a Content Delivery Network. A Content Delivery Network (CDN) is a network of servers that allows content to be distributed and delivered to users. By choosing to link to a p5.js library file hosted at the p5.js CDN, you are receiving the file from a remote server.

The p5.js CDN page has links to the recent versions of the p5.js library files. You can either copy the URL link to use as the src property of the <script> HTML tag or copy the entire <script> tag from the CDN website to include the library inside the <head> HTML element of index.html as follows:

<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.2.0/p5.min.js"></script>

Don’t worry if you don’t know where this <script> tag is supposed to go. We will talk more about it later in the article.

Optional Step: Downloading your project from p5.js web editor

If you have a project that you’ve been working on in the p5.js web editor and decide that you would like to continue working on it locally, you can do so by downloading your files. Navigate to the File drop-down menu in your project’s p5.js web editor page and click on the “Download” button. You should see a .zip file downloaded to your computer with all of the required files for running the project locally.

Unzip the downloaded file, and the complete p5.js directory structure will be available for you to access locally.

download_p5_direct

Step 4: Setting up index.html

Like a normal JavaScript program, to run any p5.js code, the sketch.js file, style.css file and all downloaded library files like p5.js need to be added into the index.html file.

Inside the <head> element of the HTML file, add the style.css file using a <link> tag and add the p5.js (or p5.min.js) file using the <script> tag. The sketch.js file can be added to the <body> element of index.html using a <script> tag as well. The sketch.js file is typically added to the <body> element because sketch.js needs to run after the p5.js library is fully loaded and ready to be used.

Your HTML file should look like this:

<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="p5.js"></script>
<meta charset="utf-8">
</head>
<body>
<script src="sketch.js"></script>
</body>
</html>

Using your preferred code editor, feel free to add this exact HTML code into your index.html file. If you decide to add the code above to your HTML file, make sure that the names of all your files match with the ones copied over.

Step 5: Adding styles to style.css

It is also essential to ensure the style.css file is appropriately set up. The CSS code below adds some basic styling to the p5.js sketch. Feel free to copy and paste it into the style.css file in your local directory.

html, body {
margin: 0;
padding: 0;
}
canvas {
display: block;
}

Step 6. Run local p5.js projects without media files

If your program does not contain any media assets, such as images, videos, and sound files, then you can run your local p5.js program by clicking on the index.html file in your project directory. This will cause your default browser to open, render, and show the output of your code from your project’s local file path. The screenshot here gives you an example of what the file path could look like when you run a local p5.js project without any media files.

Local p5.js environment with no media assets

Steps 7 and 8 do not apply to projects without media assets, so you can move directly to step 9 to learn how to debug your p5.js code. However, if your project contains media assets, opening the index.html file will not render your sketch. Continue to step 7 to learn how to set up a local server to view your projects with media assets.

Step 7. Creating a local server

If your project uses media assets, setting up a local server is necessary to avoid Cross-Origin Resource Sharing (CORS) errors when loading the webpage. CORS is a mechanism put in place to ensure web security standards are met when requests for loading resources are made.

Local servers create a way to test code without deploying it to an external web server. Essentially, they are servers deployed onto a local machine, which you can access as a local user. For more information about local servers, the processing foundation’s p5.js wiki article is a helpful resource.

There are a few ways to set up a local server using Python 2 and 3. Each method requires using the terminal if you are on Mac or Linux, or using the command prompt on Windows. If you are unfamiliar with using the terminal/command prompt, review this Command Line Interface Setup article. The article also contains information about navigating directories using terminal commands, which will be necessary to move into your project directory.

Begin by opening up your computer’s terminal or command prompt, then use the command line to navigate into the directory in which your p5.js project is located. For example, if the project’s path is User/Desktop/p5_projects/my_p5_project, you would want to navigate to the my_p5_project directory using the cd command. Once inside the directory, run the command that matches the version of Python installed on your computer.

If you have Python 2 installed on your computer, then you could use this command:

python -m SimpleHTTPServer

If you have Python 3 installed on your computer, then you could use this command:

python3 -m http.server

To check which version of Python is running on your computer, use this command:

python -V

If you are unfamiliar with Python packages and whether or not you have Python installed on your computer, check out this Installing Python 3 and Python Packages article.

Step 8: Open your local p5.js project in the browser

You are almost done with the setup! All that is left is opening your browser and typing either:

http://localhost:xxxx

Where xxxx is the specified port number, or,

http://127.0.0.1:xxxx/

Where xxxx is the specified port number.

If you used one of the commands in step 7, then the default port will be 8000. If you are unsure what port number your local server is running on, go back to your terminal to find out by reading the lines after the local server command was called.

Serving HTTP on :: port 8000 (http://[::]:8000/) ...

The screenshot shows an example p5.js sketch running on localhost on port 8000.

Local Host example running

Once you enter either of the previous localhost addresses into the browser’s URL, you should now be able to see the p5.js sketch in the browser! If you still do not see the p5.js sketch, double-check that the local server was created in the same directory as your p5.js project.

Step 9. Using the browser’s console

It is important to remember that p5.js is a JavaScript framework, and as such, a p5.js project runs like any other web project. This means that if you want to debug your code or log values to the console, you can use the browser’s development tools. The Use DevTools article dives into development tools in extensive detail if you want to learn about how to debug your web projects.

Conclusion

In this article, we learned how to set up and run a local p5.js project from scratch. We covered everything from installing a code editor, creating the necessary HTML, CSS, and JavaScript files, downloading or linking the p5.js library, and configuring a local server for media-heavy sketches. Whether you’re working with basic sketches or complex multimedia projects, running your p5.js code locally gives you greater flexibility, faster load times, and offline accessibility.

If you’re excited to improve your creative coding skills, check out Codecademy’s Learn p5.js course. This hands-on course will guide you through designing interactive visualizations and generative art using p5.js.

Frequently asked questions

1. Do I need to install p5.js to use it locally?

No installation is required. You can either download the p5.js library files to your project folder or link them using a Content Delivery Network (CDN) directly in your HTML.

2. Why isn’t my media loading when I open the index.html file locally?

Media assets like images or sounds may require a local server to load properly due to browser security restrictions. Setting up a local server prevents CORS errors.

3. How can I run a local server for my p5.js project?

You can use Python to start a local server from your project directory. Run python -m SimpleHTTPServer (Python 2) or python3 -m http.server (Python 3) in your terminal.

4. Can I transfer projects from the p5.js web editor to my local machine?

Yes! You can download a project as a .zip file from the File menu in the p5.js web editor, then unzip it and continue editing locally using your code editor.

Codecademy Team

'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'

Meet the full team