User Interaction in p5.js

Objectives and Overview

This lesson introduces two methods of user interaction in p5: keyboard and mouse events.

Lesson Objectives:

  • Demonstrate the ability to integrate user interaction in p5 by having something in your sketch change on either mouse click and/or keypress events.

Mouse Interaction

Using mouse interaction is one of the main ways to make interactive p5 sketches. Remember, p5 has built-in mouse-tracking variables – mouseX and mouseY. P5 automatically stores the mouse position data in these two variables, which can then be used as coordinates in something like an ellipse().

This process is a lot trickier when using JavaScript without p5. It’s important to remember that mouseX and mouseY are special variables provided by p5, and that they aren’t native to JavaScript. These variables, plus the other p5 functions used in this lesson, are good examples of how a library such as p5 extends the core functionality of JavaScript.

Demonstrate how mouseX and mouseY constantly update as the mouse moves across the canvas. A simple way to do this is to run through the example drawing the ellipse and showing how it’s constantly redrawn at the mouse position.

Having the background update in draw() clears the previous drawings when looping back through draw(), meaning that it’s only the most recently created ellipse showing. Consider altering the sketch to only have the background drawn once in setup and see how this creates a trail effect where an ellipse is drawn at every place the mouse has been.

Mouse Press

P5 has a built-in mousePressed() function that listens for mouse press events on the sketch. Even though this jumps ahead a bit and technically has the youth create a function, they’re tapping into something that already exists in p5’s API. They’ll be creating custom functions later in the course.

The mousePressed() function is a special function that fires automatically whenever the user clicks the left mouse button anywhere in the sketch. The mousePressed() function wraps JavaScript event listeners and simplifies the process of monitoring for user clicks. Emphasize the importance of integrating user interaction into sketches and websites, not necessarily the syntax since there is no native mousePressed() function in JavaScript. This is where it’s important to differentiate between JavaScript itself and what functionality the p5 library adds.

The provided example changes colors each time the mouse is clicked. Make sure that youth understand this functionality so that they can begin to integrate mouse interaction into their sketches.

Keyboard Interaction

This interaction taps into two additional built-in p5 functions: keyTyped() and keyPressed(). These functions monitor for user key interaction and can be stored into a variable where you can check to see if a particular key has been pressed. This jumps ahead a bit and integrates conditional statements. If the youth are having trouble with it at this point, consider moving away from this until later in the course.

What is User Interaction?

Up until this point, your sketches have been static, meaning that they’ve been fixed and unchanging. However, one of p5’s strengths is how well it enables the creation of interactive, dynamic sketches. JavaScript is a great language for creating interactive web pages, and two of the most common user interactions are the mouse and keyboard events. This lesson covers the basics of each type of interaction.

Conditional statements allow you to create programs that respond to a variety of events. Now that you have a familiarity with conditional statements you can create sketches that react to what the user does.

Mouse Interaction

The first type of user interaction is mouse events. This lesson covers two types of mouse interaction: tracking the mouse’s x and y position and reacting to mouse button presses. Understanding both of these interactions will greatly expand what you’re able to do in your p5 sketches. The basic concepts also carry over into JavaScript web programming, so try to pay attention to understanding the logic and principles behind these mouse interactions.

Mouse Position

P5 has several useful built-in variables that promote user interaction. Two of these variables are mouseX and mouseY. These variables store the mouse’s x and y positions and automatically update as the user moves their mouse. This is best demonstrated through a sketch, so let’s get started!

let col = 0; // initial value of the color function setup() { createCanvas(600,600); } function draw() { background(50); // single value for background is gray scale. fill(col); // fills with initial color value ellipse(mouseX, mouseY, 50,50); // draws ellipse at mouse position }
Code language: JavaScript (javascript)

Open up the p5 editor and rewrite that code. Once you’ve done that, click the play button and then move your mouse around in the preview window. Notice what happens!

The mouseX and mouseY variables store the position of the user’s mouse and constantly update every time draw() refreshes. The default frame rate for draw() is 60 frames per second, so the ellipse is redrawn at the mouse cursor every time you move it!

As an additional challenge, see what happens if you move the background(50) to the setup() function instead of draw(). Try it out and show the program staff!

Once you get the hang of how the mouse position variables work try integrating them into your own sketch!

Mouse Press

P5 also has a function for tracking when a user presses the left mouse button. You’ll take a deeper dive into functions in a later lesson, so for now, make sure to focus on the concept of interactivity. Being able to respond to when the user presses the mouse will allow you to add even more interactivity to your sketches. Let’s take a look at a sketch:

let col = 0; // initial value of the color function setup() { createCanvas(600,600); } function draw() { background(50); // single value for background is gray scale. fill(col); ellipse(mouseX, mouseY, 50,50); } function mousePressed() { col = color(random(0,255), random(0,255), random(0,255)); // each mousepress randomizes the color }
Code language: JavaScript (javascript)

This sketch builds on the previous one. It still tracks the x and y position of the mouse, but there is now additional interactivity contained in the mousePressed() function. If you want to use this function, you need to include it in your sketch. Whatever actions are included in the body of the function – the code included between the { } – will occur each time the user presses the left mouse button.

Add the mousePressed() function to your previous sketch and test it out! Try changing some of the code inside the function body and see what happens.

You’ll work more with functions in a later lesson. For now, just remember that if you want to add mouse press interactivity you’ll need to add this function.

Keyboard Interaction

Keyboard events are another common user interaction. The main event you’ll be using is tracking and responding to user keypresses. You’re able to assign different actions to different keypresses using conditional statements. Since this is best illustrated in an example, let’s jump in!

let col = 0; // initial value of col let bgcol = 50; //initial value of bgcol function setup() { createCanvas(600,600); } function draw() { background(bgcol); //arrow keypresses will change background color fill(col); ellipse(mouseX, mouseY, 50,50); } function keyTyped() { //keyTyped watches for user pressing letter keys if (key == 'p') { col = color(255,0,100); //if user types 'p' change color to pink } else if (key == 'g') { col = color(0, 255, 200); //if user types 'g' change color to green } } function keyPressed() { //keyPressed can be used for special characters if (keyCode == LEFT_ARROW) { bgcol = color(255); //left arrow changes background to white } else if (keyCode == RIGHT_ARROW) { bgcol = color(50); //right arrow changes background to gray } }
Code language: JavaScript (javascript)