admin管理员组

文章数量:1355697

I am using canvas with html to draw on the screen. The thing I need is to draw with the left click only, and right click just do nothing. I tried the following:

canvas.oncontextmenu = e => {
    e.preventDefault();
    e.stopPropagation();
}

It disabled the right click menu, but I am able to press the canvas (and eventually draw on it) with both left and right click. What am I missing?

I am using canvas with html to draw on the screen. The thing I need is to draw with the left click only, and right click just do nothing. I tried the following:

canvas.oncontextmenu = e => {
    e.preventDefault();
    e.stopPropagation();
}

It disabled the right click menu, but I am able to press the canvas (and eventually draw on it) with both left and right click. What am I missing?

Share Improve this question edited Oct 24, 2019 at 15:24 TheCondorIV 6142 gold badges15 silver badges34 bronze badges asked Oct 24, 2019 at 7:44 user12267069user12267069
Add a ment  | 

5 Answers 5

Reset to default 3

try:

<canvas oncontextmenu="return false;"></canvas>

You can use this:

canvas.bind('contextmenu', function(e){
    return false;
}); 

Using Jquery:

$('body').on('contextmenu', '#myCanvas', function(e){ return false; });

Try the following:

const canvas = document.getElementById('myCanvas');
canvas.oncontextmenu = () => false;

where myCanvas is eventually the ID given to the canvas, i.e.

<canvas id="myCanvas"></canvas>

Try this:

canvas.addEventListener('mousedown', (event) => {
  if (event.which !== 1) {
    event.preventDefault();
  }
});

It should also disable context menu from appearing. Clicking the middle mouse button won't give any effect too.

event.which contains the index of mouse button that is pressed. 1 is the left button, 2 is the middle, 3 is the right one. preventDefault() prevents default browser behaviour from being executed (such as opening context menu etc, it can be applied in many situations).

By the way, stopPropagation() is used to stop such events (as context menu opening, in this case) from being executed at child elements. <canvas> doesn't have child tags, so it can be omitted.

本文标签: javascriptDisable right click on canvasStack Overflow