HomeLanguagesJavascriptp5.js mousePressed() Function

p5.js mousePressed() Function

The mousePressed() function in p5.js works when mouse clicked on the document. The mouseButton variable is used to specify which button is pressed. The touchStarted() function is used instead of mousePressed() function if mousePressed() function is not defined.

Syntax:

mousePressed(Event)

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

Example 1: This example uses mousePressed() function.




function setup() {
      
    // Create Canvas
    createCanvas(500, 500);
}
   
let value = 0;
  
function draw() {
      
    // Set background color
    background(200);
      
    // Fill the color
    fill(value, value-50, value-100);
      
    // Create rectangle
    rect(25, 25, 460, 440);
      
    // Set the color of text
    fill('lightgreen');
      
    // Set font size
    textSize(15);
      
    // Display content
    text('Keep on Clicking the Mouse Across'
        + 'the page \nto change Canvas Color.',
            windowHeight/10, windowWidth/4);
}
  
function mousePressed() {
      
    value = value + 5;
      
    if (value > 255) {
        value = 0;
    }
}


Output:

Example 2:




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


Output:

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

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32688 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
7057 POSTS0 COMMENTS
Nicole Veronica
12198 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12293 POSTS0 COMMENTS
Shaida Kate Naidoo
7182 POSTS0 COMMENTS
Ted Musemwa
7447 POSTS0 COMMENTS
Thapelo Manthata
7160 POSTS0 COMMENTS
Umr Jansen
7150 POSTS0 COMMENTS