最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Disable right click on canvas - Stack Overflow

programmeradmin1浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论