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() {
createCanvas(500, 500);
}
let value = 0;
function draw() {
background(200);
fill(value);
rect(25, 25, 460, 440);
fill( 'lightgreen' );
textSize(15);
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() {
createCanvas(500, 500);
}
function draw() {
background(200);
fill( 'green' );
textSize(25);
text( 'Drag mouse to change color' , 30, 30);
fill(value, 255-value, 255-value);
ellipse(mouseX, mouseY, 115, 115);
}
function mouseDragged() {
value = mouseX%255;
}
|
Output:

Reference: https://p5js.org/reference/#/p5/mouseDragged
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks 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!
Last Updated :
18 Aug, 2023
Like Article
Save Article