Open In App

p5.js mouseWheel() Function

The mouseWheel() function is invoked whenever a mouse or touchpad scroll causes a vertical mouse wheel event. This event can be accessed to determine the properties of the scroll. The delta property returns the amount of the scroll that took place. This value can be positive or negative depending on the direction of the scroll.

The callback function may have to end with the “return false;” statement to prevent any default behaviors that may be associated with scrolling on different browsers.



Syntax:

mouseWheel( event )

Parameters: This function accepts a single parameter as mentioned above and described below:



Below examples illustrate the mouseWheel() function in p5.js:

Example 1: Using the scroll event to change the color when scrolled




let red = 0;
   
function setup() {
    createCanvas(750, 300);
    textSize(24);
}
   
function draw() {
    clear();
   
    // Apply fill based on the
    // red component
    fill(red, 0, 0)
   
    text("Scroll the mouse wheel to "
            + "change the red component"
            + " of the color", 20, 20);
      
    circle(150, 150, 200);
}
   
function mouseWheel(event) {
    
    // Change the red value according
    // to the scroll delta value
  red += event.delta;
}

Output:

Example 2: Displaying the scroll properties




let scrollDelta = 0;
   
function setup() {
    createCanvas(500, 200);
    textSize(24);
    text("Scroll the mouse to see the"
        + " scroll details.", 10, 20);
}
   
function mouseWheel(event) {
    scrollDelta = event.delta;
   
    clear();
    deltaString = "Current mouse delta is: "
                    + scrollDelta;
    
    text(deltaString, 10, 20);
   
    if (scrollDelta > 0) {
        text("You are scrolling downwards", 10, 40);
    
    else {
        text("You are scrolling upwards", 10, 40);
    }
}

Output:

Online editor: https://editor.p5js.org/
Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/amp/

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


Article Tags :