This is an old revision of the document!


p5js: making interactive sketches

We talked about using mouseX and mouseY in this lesson:

https://renickbell.net/doku.php?id=p5js-week-02

Let's go deeper on making our sketches interactive.

Think about what data the mouse can give you:

  1. X position
  2. Y position
  3. button clicks
  4. button releases
  5. double-clicks

p5js also has some functions that deal with mouse position relative to the previous frame, including detecting mouse movement, mouse dragging, and whether the left button is pressed. There's also a function for mouse wheel, but mouse wheels are not always implemented on mice or may be implemented in different ways.

tracking the mouse

In the following example, we make a box follow the mouse.

You can read more about mouseX and mouseY here:

https://p5js.org/reference/#/p5/mouseX

https://p5js.org/reference/#/p5/mouseY

That's cool, but let's move the mouse to the center of the box. Notice that this example first declares variables for the width and height. This allows us to reuse them and later will let us more easily experiment with our code.

Let's blow up the rect from our previous example when the left button of the mouse is pressed.

There's more on this here:

https://p5js.org/reference/#/p5/mouseIsPressed

On my laptop, mouseButton == CENTER seems buggy in this example: https://p5js.org/reference/#/p5/mouseButton

In this version, we'll make the rect get smaller when the mouse moves. At the same time, we'll make the animation a little smoother.

In this version, let's show the mouse position value like we did before, and then let's do some math with that value to change our sketch.

Let's gather the mouse position from each click and use it.

  • p5js-interaction.1708584426.txt.gz
  • Last modified: 3 months ago
  • by renick