简体   繁体   中英

Block right clicks in canvas with WebGL context

I want to stop the right mouse button on a HTML5 canvas bringing up the context menu, since it gets in the way of mouse-controlled games.

I've tried adding oncontextmenu="return false;" to the canvas tag attributes. This works when the canvas is using a 2D context, but not when it uses a WebGL context, in both Firefox and Chrome.

Is this somehow specified by the standard or is it two simultaneous browser bugs? Is there any way to work around this and block right clicks in a WebGL context?

Results may vary per browser so ensure this works on all targeted browsers. I only tried it in Chrome.

  yourCanvas.addEventListener('contextmenu', function(e) {
      if (e.button === 2) {
       e.preventDefault();
        return false;
      }
  }, false);

Working example: http://jsfiddle.net/cK9Rt/

(it will say "test" in the console but not make the context menu)

I use the following code when blocking a default browser action

element.onevent=function(e){
    e.preventDefault();
    return false;
}

This code makes absolutely sure that the default action will not occur

never use html attributes to prevent the default.

When I saw your question, I tried this under the same circumstances:

canvas.oncontextmenu=function(e){
    e.preventDefault();
    return false;
}

And it worked exactly as it should.

I hope this helps any future viewers of this question

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM