Disabling right click context menu on a HTML Canvas?

前端 未结 6 1755
醉梦人生
醉梦人生 2021-02-05 00:45

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

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-05 01:10

    Avoiding dependence on Jquery Js, I have tried the preventDefault event not only with canvas but also in other elements. Regarding the crossBrowser I reviewed this page: Events - Contextmenu.

    You probably need a validation of items that return undefined but it serves as a demonstration.

    (function(w, d){
    	d.body.addEventListener('contextmenu', function(event){
    		var blockContext = [
    			{ type: 'tag', value: 'canvas'},
    			{ type: 'id',  value: 'fooId'},
    			{ type: 'tag',  value: 'img'},
    		];
    		blockContext.map(
    			elm => {
    				var _elm
    				
    				if(elm.type == 'tag') _elm = d.querySelector(elm.value);
    				if(elm.type == 'id') _elm = d.getElementById(elm.value);
    
    				if(event.target == _elm) event.preventDefault();
    			}
    		);
    	});
    })(window, document);
    canvas {
    background-color: grey;
    }
    
    
    

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin eget lorem luctus nisi fermentum imperdiet in ac tortor. Vestibulum interdum risus vitae metus finibus pretium. Nullam facilisis lacus nec pellentesque faucibus. In tempus lorem ut mi sodales, vitae scelerisque quam pretium. Duis venenatis enim in nunc laoreet venenatis. Aliquam at magna vitae purus tincidunt posuere. Donec dictum pharetra ipsum, eu auctor lorem aliquet vitae. Donec faucibus metus quis laoreet ultricies. Aliquam aliquet, lectus a tempor tristique, diam sem auctor felis, sed ultrices magna nunc ut sem. Curabitur congue diam lacinia risus sodales luctus. In nec maximus ex. Nulla ultrices diam a erat imperdiet, nec convallis nisl pulvinar. Etiam quis placerat arcu, eu elementum felis. Phasellus lectus massa, faucibus faucibus nibh ut, dignissim tempor neque.

提交回复
热议问题