javascriptmouseeventp5.js

p5.js on right mouse click shows the browser context menu and not the drawing function


I have this function in P5.js :

function mousePressed() {
    if (mouseButton === LEFT) {
        background(255);
        canvas2.clear();
        canvas3.clear();
    }
    if (mouseButton === RIGHT) {
        canvas3.clear();
        canvas3.fill(0, 0, 0);
        canvas3.stroke(0, 0, 0);
        canvas3.rect(80, 180, 40, 40);
    }
}

And it works perfectly , but.... When I click mouse-rightclick , the browser context menu shows-up (Save image as..., Copy image..., Inspect Ctrl+Shift+I). How to disable this or change the behavior?


Solution

  • This is no popup alert but the browsers shortcut menue: Steps to do:
    It seems like a good idea to prevent the default behavior of the browser:

     document.addEventListener('contextmenu', event => event.preventDefault());
    

    That being said: DON'T DO IT.

    Why? Because it achieves nothing other than annoying users. Also many browsers have a security option to disallow disabling of the right click (context) menu anyway. So we go for the other events fired when right click is issued

    and then you should proceed as follows Set a state flag when the event occurs:

     var rightPressed = false;
    
     function mouseClicked() {
         if(mouseButton === RIGHT) {
            rightPressed = true;
         }
      }
    

    Reset the flag when the action which is triggered by the event was handled:

     function draw() {
    
      if (rightPressed) {
             rightPressed = false
    
            // do somthing
        // ...
        } 
     }
    

    Hope this helps you