Submodule 17.1: Events

mouseX and mouseY

Two of the p5.js events are the mouseX and mouseY.

mouseX holds the horizontal position at which the user points its mouse. It changes everytime the user moves its mouse horizontally. 

Similar to mouseX, mouseY holds the vertical position at which the user holds its mouse. 

Example 

Here is an example code which creates a simple drawing tool: 

function setup() {
  createCanvas(windowWidth, windowHeight);
  // set background color in the setup so sketches will leave traces
  background('#D66761');
}
function draw() {
  noStroke();
  fill(241, 222, 152, 30);
  // ellipse will change according to the mouseX and mouseY position
  ellipse(mouseX, mouseY, 30, 30);
}

You can see the result of the above code, click here.

Exercise

  1. Open your Visual Studio editor and the p5yourName folder.
  2. Open the file ex812.js in your editor and save it as ex912.js
  3. Open the file ex812.html in your editor and save it as ex912.html
  4. In the ex912.html file, update the link to ex912.js  from exersice812.js
  5. Go to the index.html file and create, under Module 9, a link to the ex912.html  file with the title "mouseX and mouseY".

Modify the ex912.jsfile to create an ellipse that will change color according to the mouseX and mouseY position. You can see here an example.

Answer:

function setup() {
  createCanvas(800, 500);
  // set background color 
  background('#D66761');
}
function draw() {
  // we use mouseX in order to control the green value of the color
  // we divide it by 4 so that the value will not exceed 256
  // for the blue value we use mouseY divided by 2
  fill(241, mouseX/4, mouseY/2);
  // ellipse will change color according to mouseX and mouseY position
  ellipse(400, 250, 200);
}

Do a Git commit with the message "mouseX and mouseY".

  • See more about the mouseX event
  • See more about the mouseY event