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
- Open your Visual Studio editor and the
p5yourName
folder. - Open the file
ex812.js
in your editor and save it asex912.js
- Open the file
ex812.html
in your editor and save it asex912.html
- In the
ex912.html
file, update the link toex912.js
from exersice812.js - Go to the
index.html
file and create, underModule 9
, alink
to theex912.html
file with the title "mouseX and mouseY".
Modify the ex912.js
file to create an ellipse that will change color according to the mouseX and mouseY position. You can see here an example.
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".