javascript - Disable right click on canvas - Stack Overflow

I am using canvas with html to draw on the screen. The thing I need is to draw with the left click only

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744034158a4547105.html

相关推荐

  • javascript - Disable right click on canvas - Stack Overflow

    I am using canvas with html to draw on the screen. The thing I need is to draw with the left click only

    9天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信