Home » Html » Disabling right click context menu on a HTML Canvas?

Disabling right click context menu on a HTML Canvas?

Posted by: admin November 30, 2017 Leave a comment

Questions:

Making a painting app using HTML5 and Canvas.

I think I want to have a similar system to applications like Paint and Photoshop where you can have a primary and secondary color selected and use left click to paint with the primary color and right click to paint with the secondary color.

However, after one releases the right mouse button the context menu in the browser is brought up (view image, save image, select all).

Can this be elegantly disabled? I don’t want it to be a hackish solution that only works on some browsers if possible.

Thanks.

Answers:

You can use this:

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

See this working example!

With the lastest jQuery:

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

Note: You should use something narrower than body if possible!


EDITED

Updated the Fiddle Example to show the contextmenu being limited to the canvas and not the image.

JQUERY

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

HTML EXAMPLE

<canvas id="myCanvas" width="200" height="100">
  Your browser does not support the canvas element.
</canvas>

<img src="http://db.tt/oM60W6cH" alt="bubu">

Questions:
Answers:

Try this

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

Questions:
Answers:

Try adding oncontextmenu="return false;" on the body tag. It should disable the context menu.

If I believe this source : http://javascript.about.com/library/blnoright.htm which is google’s first result to the query “javascript disable right click” that you should have tried.

Edit :

  • about canvas I don’t know the element, but did you try calling
    stopPropagation() on the event element once your function ends ?
  • or the previous solution on the canvas tag instead of the body…
Questions:
Answers:

This will disable the context menu on the canvas.

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