How to add mouse interaction in p5.js

Mouse interaction allows users to manipulate or control the application using mouse positions and clicks. The p5.js has built-in functions that allow for such interactions to take place.

Mouse interaction

To use the mouse to interact with the p5.js application, we can use the global variable, the mouseIsPressed, to check when the mouse has been pressed. This variable is true when the mouse button is clicked, and false when it is not.

We can also use the global variables,Global variables are accessible anywhere in the code. the mouseX and mouseY, to track the mouse's position.

Let’s look at a few sample cases.

Example: Paint

Take a look at the example below. In this example, we can see the use of the mouseIsPressed, and the mouse's position. Click the mouse to draw something onto the canvas.

Code explanation

  • Lines 2–12: The size variable stores the size of the "brush." The setup() function sets up the application canvas and the background.

  • Lines 14–26: In the draw() function, whenever the mouseIsPressed is true, an ellipseAn ellipse is a circular shape with no edges. is drawn at the mouse's position, with the size variable controlling the diameter. Before drawing the ellipse, we use the noStroke() function to remove the strokeStroke is the border around a shape..

Example: Crosshair

Take a look at the example below, in which we can see the mouseX and mouseY variables being used to draw shapes. We will see that wherever we move the mouse on the canvas, we will see a crosshair.

Code explanation

  • Lines 3–6: The setup() function is called once at the start of the execution. This function sets up the application canvas.

  • Lines 8–17: The draw() function is called once every frame. In this function the background is being reset, and the fillFill is the color of a shape. and strokeIn case of lines, the stroke color acts as the line color. color is being set.

  • Lines 20–25: The ellipse() function is being used to draw one ellipse at mouseX and mouseY. The line() function is being used twice to draw two lines — a vertical line and a horizontal line. The vertical line is at mouseX, that spans the height of the canvas. The horizontal line is at mouseY, that spans the width of the canvas.

Conclusion

The p5.js allows the user to implement mouse interactions in a simple way. There are also other functions like the mousePressed()This function is called whenever a mouse click is detected. and mouseReleased()This function is called whenever a mouse click is released. that we can use to perform more complex mouse interactions.

Unlock your potential: p5.js fundamentals series, all in one place!

If you've missed any part of the series, you can always go back and check out the previous Answers:

Free Resources

HowDev By Educative. Copyright ©2025 Educative, Inc. All rights reserved