The mouseMoved() function in p5.js is called every time the mouse moves and a mouse button is not pressed.
Syntax:
mouseMoved(Event)
Parameters: This function accepts single parameter Event which is optional.
Below programs illustrate the mouseMoved() function in p5.js:
Example 1: This example uses mouseMoved() function change the rectangle color when mouse move over.
function setup() {
// Create Canvas of size 500*500
createCanvas(500, 500);
} let value = 0; function draw() {
// SEt background color
background(200);
// Set the filled color
fill(value);
// Create rectangle of given size
rect(25, 25, 460, 440);
// Set the text color
fill( 'lightgreen' );
// Set font size
textSize(15);
// Display the text
text( 'Move Mouse Across the page to change its value.' ,
windowHeight/6, windowWidth/4);
} function mouseMoved() {
value = value + 5;
if (value > 255) {
value = 0;
}
} |
Output:
Example 2: This example uses mouseMoved() function change the color of ellipse.
// Declare a variable let value; function setup() {
// Create Canvas of size 500*500
createCanvas(500, 500);
} function draw() {
// Set background color
background(200);
// fill color according to
// mouseMoved() function
// Set the color
fill(value, value, value);
// Draw ellipse
ellipse(mouseX, mouseY, 115, 115);
} function mouseMoved() {
value = mouseX%255;
} |
Output:
Reference: https://p5js.org/reference/#/p5/mouseMoved