p5.js | Mouse | 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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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;
    }
}

chevron_right


Output:

Example 2: This example uses mouseMoved() function change the color of ellipse.

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Output:

Reference: https://p5js.org/reference/#/p5/mouseMoved



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.