p5.js | Mouse | mouseDragged() Function

The mouseDragged() function in p5.js is used to check the mouse drags (mouse moves and mouse button pressed). It is invoked each time when the mouse drags. If mouseDragged() function is not defined, then touchMoved() function will be used instead of mouseDragged() function.

Syntax:

mouseDragged(Event)

Below programs illustrate the mouseDragged() function in p5.js:

Example 1: This example uses mouseDragged() function to change the background color.

filter_none

edit
close

play_arrow

link
brightness_4
code

function setup() {
  
    // Create Canvas
    createCanvas(500, 500);
}
   
let value = 0;
  
function draw() {
      
    // Set background color
    background(200);
      
    // Set filled color
    fill(value);
      
    // Create rectangle
    rect(25, 25, 460, 440);
      
    // Set text color
    fill('lightgreen');
      
    // Set font size
    textSize(15);
      
    // Display result
    text('Drag Mouse Across the page to change its value.',
        windowHeight/6, windowWidth/4);
}
  
function mouseDragged() {
    value = value + 5;
      
    if (value > 255) {
        value = 0;
    }
}

chevron_right


Output:

Example 2: This example uses mouseDragged() function to change the mouse cursor circle color.

filter_none

edit
close

play_arrow

link
brightness_4
code

let value;
  
function setup() {
      
    // Create Canvas
    createCanvas(500, 500);
}
   
function draw() {
      
    // Set background color
    background(200); 
      
    // Set filled color
    fill('green');
      
    // Set text and text size
    textSize(25);
      
    text('Drag mouse to change color', 30, 30);
      
    // Fill color according to
    // mouseMoved() function
    fill(value, 255-value, 255-value);
      
    // Draw ellipse  
    ellipse(mouseX, mouseY, 115, 115);
}
  
function mouseDragged() {
    value = mouseX%255;
}

chevron_right


Output:

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



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.