Reputation:
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?
Upvotes: 5
Views: 2482
Reputation:
Using Jquery:
$('body').on('contextmenu', '#myCanvas', function(e){ return false; });
Upvotes: 2
Reputation:
You can use this:
canvas.bind('contextmenu', function(e){
return false;
});
Upvotes: 2
Reputation: 382
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.
Upvotes: 0
Reputation:
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>
Upvotes: 0