Skip to content
Related Articles

Related Articles

Improve Article

p5.js | Mouse | mouseDragged() Function

  • Last Updated : 22 Apr, 2019
Geek Week

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.




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

Output:



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




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

Output:

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

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it’s lowest price ever!




My Personal Notes arrow_drop_up
Recommended Articles
Page :