Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disabling right click context menu on a HTML Canvas?

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.

like image 486
Ryan Peschel Avatar asked Jun 02 '12 16:06

Ryan Peschel


People also ask

How do I hide the context menu in right click?

The context menu usually has a list of actions like "View Page Source" and "Back". We can prevent this menu from appearing on right-click by latching onto the contextmenu event and using event. preventDefault() . If we add this event listener to the window object then we can prevent right-clicking on the whole page.

How do you disable right click using HTML?

Disable right click menu in html page using jquery. JavaScript Code: $(document). bind("contextmenu",function(e){ return false; });


2 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!

Or without jQuery, applying on canvas:

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

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"> 
like image 67
Zuul Avatar answered Sep 30 '22 10:09

Zuul


Try this

canvas.oncontextmenu = function (e) {     e.preventDefault(); }; 
like image 28
Andrew Nodermann Avatar answered Sep 30 '22 09:09

Andrew Nodermann