Open In App

p5.js mouseMoved() Function

Last Updated : 04 Mar, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report
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. javascript
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. javascript
// 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

Next Article

Similar Reads