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

Viewed 1761

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?

3 Answers

p5.js' canvas element conveniently has the p5Canvas class assigned to it when it's created. We could find all DOM elements with that class and prevent the context menu action only for those elements. Something like this would do:

function setup() {
  for (let element of document.getElementsByClassName("p5Canvas")) {
    element.addEventListener("contextmenu", (e) => e.preventDefault());
  }
}

This way we avoid the frustration of not being able to open the context menu anywhere while still being able to define our own right-click functionality without triggering the context menu.

It's important that the code be executed after the initial setup, though, since the canvas DOM element is generated at p5 runtime.

The createCanvas() function returns a p5.Element whose .elt member is the DOM node. As such, you can use @bluelhf's code directly:

function setup() {
  const canvas = createCanvas(width, height)
  canvas.elt.addEventListener("contextmenu", (e) => e.preventDefault())
}

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

Related