I’ve wanted to try p5js for quite a long time. Last week I decided to dive into the unknown and create a simple game with that in one single Saturday night to see how it works. I chose the popular ‘aa’ game, in which the player tosses pins on a spinning target avoiding colliding with any other pin already on the target.

I was intimidated by p5js, then I quickly found the library really really user-friendly and intuitive. It was simple to get started, and I rapidly mastered the structure, shapes, colors, and animations.

One of the things I liked best about p5js is the abundance of materials. There are numerous online tutorials and examples to help you in getting started and troubleshoot any problem you may face. This made it easier for me to work on the game and solve any bugs I found.

Here is a quick starting guide. Start by making a simple HTML file with a link to the p5js library cdn right in the <head> section:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>My Fabulous App</title>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.5.0/p5.min.js"></script>
    </head>
    <body>
        <script>
            // Your p5js script goes here
        </script>
    </body>
</html>

And that’s it. Now, you can start writing p5js code in the script tag. Here’s a simple example to create a canvas and draw a circle on it:

let circlePosition;

function setup() {
    // create base canvas
    createCanvas(320, 480);

    // create a vector to the middle of the screen
    circlePosition = createVector(width/2, height/2)
}


function draw() {
    // draw background
    background(220);

    // draw a circle
    fill([255, 0, 0]);
    circle(circlePosition.x, circlePosition.y, 50);

    // update the circle
    circlePosition.x++
    circlePosition.y++

    // relocate if out of bound
    if (circlePosition.x > width) circlePosition.x = 0
    if (circlePosition.y > height) circlePosition.y = 0
}

At the beginning of the program, setup() function is called once. This creates a canvas with a given size. To update the canvas, draw() function is called over and over at every rendered frame. This makes it very easy to write the logic of the game and animations here. Our draw() function in the example makes the background a light gray color (220 out of 255), fills a circle with red ([R, G, B] array of the color), and draws it in the middle of the canvas. Then for each frame we update the location of that. Finally it check whether the circle is out of boundaries of our screen. Note that width and height are injected to your code. It comes from the display window set with createCanvas() method.

This is just a simple example. You can do a lot more with p5js, like make animations, make things interactive, and define keyboard and mouse functionalities. Check out the source code and the chrome extension for the game I made.

aa

👉 Get The Extension

🔁 Github Repo