p5.js is a powerful library that enables creative coding in the web environment. To harness its powers, you need to set up your environment and learn the basics of using p5.js. This article will guide you through that process.
Step 1: Downloading the p5.js Library
Head over to the p5.js download page and download the latest version of the library. You can choose between the complete, minified, or the CDN-hosted version. For beginners, the complete version is recommended, as it includes helpful error messages.
Step 2: Create Your Project Folder
Create a new folder for your project, and name it something descriptive, like "p5js-project". Inside the project folder, create two new files:
Step 3: Setting Up the HTML File
index.html file in your text editor of choice, and add the following basic HTML structure:
Make sure to replace the
path/to/p5.js with the actual path to the p5.js file you downloaded earlier.
Step 4: Writing Your First p5.js Sketch
sketch.js file, and add the following code:
This code creates a simple sketch with a 640x480 canvas and a background color of 200 (a light gray). The
draw() function uses an if-else statement to change the color of the ellipse, depending on whether the mouse is pressed or not.
Step 5: Running Your p5.js Sketch
To run your sketch, simply open the
index.html file in your web browser. You should see a gray canvas, and when you click and drag your mouse, an ellipse should follow your cursor.
Congratulations! You've successfully set up the p5.js environment and created your first sketch. Now you can dive deeper into the library and explore its functions and features.
How do I download the p5.js library?
Visit the p5.js download page (https://p5js.org/download/) and choose between the complete, minified, or CDN-hosted version. For beginners, the complete version is recommended, as it includes helpful error messages.
What are the basic files I need for a p5.js project?
You need two files for a basic p5.js project:
index.html file contains the HTML structure and script references, while the
sketch.js file contains your p5.js sketch code.
How do I run my p5.js sketch?
To run your p5.js sketch, simply open the
index.html file in your web browser. Your sketch should run, and you should be able to interact with it using your mouse and keyboard.