Skip to content

Mouse Interaction

Jolon Faichney edited this page Mar 17, 2017 · 3 revisions

Computers by their very nature are interactive. They take input, process it, and output a response.

One common form of input is the mouse (which may also be touch on a touchscreen).

There are two ways we can access information about the mouse:

  1. Mouse variables
  2. Event handling functions

We will first look at the available mouse variables.

Mouse Variables

You can find information about the available mouse variables under the Events section of the p5.js reference.

We are going to look at the following mouse variables:

  • mouseX - x co-ordinate location of the mouse in the canvas
  • mouseY - y co-ordinate location of the mouse in the canvas
  • mouseIsPressed - true if the mouse is pressed, false otherwise

mouseX and mouseY

mouseX and mouseY simply contain the current location of the mouse. So it is simple, for example, to draw something at that location.

In the following example the ellipse follows the mouse around the screen. If we don't redraw the background, it leaves a trail of ellipses, like a paint brush, or drawing program. We can do interesting things like continually change the colour of the ellipse (or paint brush).

function draw() {
  ellipse(mouseX, mouseY, 20, 20);
}

We can see how simple it is to create interactive interfaces with p5.js.

To move the ellipse instead of draw with it, simply repaint the background:

function draw() {
  background(100);
  ellipse(mouseX, mouseY, 20, 20);
}

Alternatively we can change the colour of the ellipse:

var r = 0;
var direction = 1;
function draw() {
  fill(r, 100, 100);
  ellipse(mouseX, mouseY, 20, 20);
  r = r + direction;
  if (r >= 255) {
    direction = -1;
  }
  if (r <= 0) {
    direction = 1;
  }
}

Note that I needed to use the variable r instead of red as red is already used by the system.

Note also that the code looks very similar to our bounce code. When performing frame based animation you will see this type of code commonly, where a variable bounces between two variables. The proper term is linear interpolation.

mouseIsPressed

We can change the previous code so that it only rotates between colours if the mouse is pressed!

mouseIsPressed has the value true when the mouse is pressed and false otherwise. Most programming languages, including JavaScript have the values true and false. These are known as boolean values and we will cover them more later.

var r = 0;
var direction = 1;
function draw() {
  fill(r, 100, 100);
  ellipse(mouseX, mouseY, 20, 20);
  if (mouseIsPressed) {
    r = r + direction;
  }
  if (r >= 255) {
    direction = -1;
  }
  if (r <= 0) {
    direction = 1;
  }
}

You can see the example running here.

Next: Booleans

Clone this wiki locally