What is p5.js?
Getting Started with p5.js
To begin using p5.js, all you need to do is include the p5.js library in your HTML file, like so:
With the library included, create a new file called
sketch.js. This is where you'll write your p5.js code. The p5.js library provides two essential functions:
setup() function is executed once when the program starts and can be used for initializing variables, setting up the canvas, and other setup tasks. In this example, we create a canvas with a width of 800 pixels and a height of 400 pixels.
draw() function is called continuously, creating a loop. In this example, it sets the background color to white (255) and draws a circle (ellipse) at the center of the canvas with a width and height of 50 pixels.
Creative Coding with p5.js
p5.js offers a wide range of functions for drawing shapes, manipulating colors, working with typography, and handling user input. Here's a simple example of an interactive sketch that changes color based on mouse position:
In this example, we use the
map() function to convert the mouse's x and y positions to RGB color values. The background color is then set to these values, creating an interactive, color-changing canvas.
Beyond the Basics
p5.js is a versatile library with a vast ecosystem of add-ons and community-contributed libraries. You can explore further possibilities like 3D graphics, audio synthesis, and even computer vision!
Dive into the world of p5.js, and let your imagination run wild as you create mesmerizing visuals and engaging interactive experiences. The only limit is your creativity!