Saturday, October 25, 2025
HomeLanguagesJavascriptp5.js mouseMoved() Function

p5.js mouseMoved() Function

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

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS