Prevent left click on HTML canvas and enable right click to pass through with pointer-events

In my scenario, I have an HTML canvas positioned above various other HTML elements that detect right-click mouse events. The goal is to be able to draw on the canvas with the left mouse button while simultaneously interacting with the underlying HTML elements using the right mouse button.

I understand that setting the CSS property "pointer-events" to "none" allows all mouse events to pass through the canvas. However, I specifically want only right-click events to pass through.

One possible solution could involve listening for right-click events on the canvas, then in the callback, setting "pointer-events" to "none", manually triggering a right-click event, and then reverting "pointer-events" back to "auto".

For context, I'm utilizing KineticJS, and I am unsure of how to manually trigger mouse events using this library.

If anyone has any suggestions or insights on accomplishing this task, they would be greatly appreciated.

Answer №1

Engaging topic that captured my interest. It was enjoyable to devise a solution for it using this jQuery technique among others. Although I am not acquainted with KineticsJS, this method utilizes plain JavaScript.

In summary, you can simulate a pointer-events:none specifically for right-click by leveraging the object's dimensions and positioning along with onmousedown's event.which to identify if a right-click occurred on the background elements. The code snippet below demonstrates this approach, with explanatory comments included.

// Retrieve all overlaying canvases
var canvas = document.getElementsByTagName("canvas"); 
// Fetch all elements where the click should register
var background = document.getElementsByClassName("background"); 

// Employ mouse location and element details to allow clicks to pass through
function passThrough(e) { 
    // Permit only right-click events to pass through
    if (e.which == 2 || e.which == 3) { 
        // Iterate through all background elements
        for (var i = 0; i < background.length; i++) { 
            // Check if clicked point (obtained from event) is within the element
            var mouseX = e.pageX;
            var mouseY = e.pageY;
            var obj = background[i];
            var width = obj.clientWidth;
            var height = obj.clientHeight;

            if (mouseX > obj.offsetLeft && mouseX < obj.offsetLeft + width 
                && mouseY > obj.offsetTop && mouseY < obj.offsetTop + height) {
                // Trigger click event if within boundaries
                background[i].onclick(); 
            }
        }
    }
}

for (var i = 0; i < canvas.length; i++) {
    // Invoke our function upon click
    canvas[i].onmousedown = passThrough; 
    // Prevent context menu from appearing
    canvas[i].oncontextmenu = function(event) { event.returnDefault; return false; } 
}
for (var i = 0; i < background.length; i++) {
    // Toggle background color upon click (to demonstrate functionality)
    background[i].onclick = function() { 
        if (this.style.background == "black") {
            this.style.background = "red";
        }
        else {
            this.style.background = "black";
        }
    }
}

http://jsfiddle.net/z7TUX/3/

I trust this meets your requirements!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Material UI dialog is causing issues for CKEditor 4

In the midst of my React project, I have incorporated CKEditor 4 into a Material UI dialog. However, when attempting to utilize advanced features like Math, I encounter an issue where I am unable to input any text into input or textarea fields. Despite sea ...

Removing a specific row in a database table and sending a boolean indicator to an API, all while keeping the original object intact

I'm currently working on a spa project using AngularJS and integrating an api with mvvm in C#. One issue I am facing is that when I click the delete button, it deletes the line but I only want to change a boolean flag to true on the server side while ...

Click to start viewing the video

I'm attempting to have a video play when clicked, either on the video itself or around the video. There are multiple videos on the page and I've tried various solutions including the script below which didn't work. $('video'). ...

Search timeout restriction

I have a function that makes a request to the server to retrieve data. Here is the code for it: export default class StatusChecker { constructor() { if (gon.search && gon.search.searched) { this.final_load(); } else { this.make_req ...

What is the best way to include rxjs in an npm library - as a dependency, peer dependency, or both?

After researching numerous posts and articles on dependencies versus peerDependencies, I am still not entirely certain what to do in my particular situation.... I have a library (which is published to a private npm repository) that utilizes rxjs; for exam ...

5 steps to create a versatile function for activating attributes based on their values

Hey everyone! I was working on creating this calculator and I had different options to implement it, but I wanted to do it in a specific way. <form action=""> <label for="num1">Number A</label><br> <input type="number" na ...

Add elements to an array following an AJAX request

On my .cshtml page, I have the following script: $(function () { var tempArray = []; var tbValue = $('#tb1').val(); $.ajax({ url: "/ControllerName/getdata", dataType: 'json', ...

Storing HTML values in a Meteor database is a common practice for web

Within my meteor project, I have a paragraph in HTML containing a JSON value as follows: {"Active Template Id":"6467","Shirt Brand":"levis","ProductId":"EB301","Brand":"on","Material":"cotton","Price":"1800","Combo Id":"S90"} I am looking to store this v ...

Adding a Row to an HTML Table Inside a Form through JavaScript

I'm currently attempting to insert a row into a table that resides within a form using JavaScript. The strange thing is, the code functions perfectly when it's placed outside of the form tags. However, as soon as I enclose the code within the for ...

Error 403 with Google Search Console API: Access Denied

Currently, I am attempting to extract data from the GSC Search Analytics API using Python. Despite diligently following this resource, I have encountered an error that persists despite multiple attempts to remedy it: raise HttpError(resp, content, uri=se ...

Discovered an issue with AngularJS involving ng-show and ng-if?

Upon my investigation, I have identified multiple issues with angularjs: <div ng-show="['[]']">this should be displayed but it is not working as expected</div> <div ng-show="[]">this should be displayed but it is not working as ...

Add hyphens to separate the words in AngularJS if there is a break in the string

Within a div of set width, a string is being bound to it. This string could be short or long. I would like for the string to break with a hyphen inserted on each line except for the last one. For example: If the string is "misconception" and it breaks at ...

Show a button using CSS when the cursor is hovering

Expressing my gratitude to everyone! I need assistance with implementing a function in reactJS where the <button /> remains hidden during page loading and reveals itself when hovered over. Despite trying various methods, I have been unable to resolve ...

Accessing the media player of your system while developing a VSCode extension using a nodejs backend: A comprehensive guide

I am currently utilizing the play-sound library in my project. I have experimented with two different code snippets, each resulting in a unique outcome, none of which are successful. When I implement const player = require('play-sound')({player: ...

"RecognitionAudio variable missing" and "InactiveRpcError occurred" [Utilizing the Google text-to-speech API]

I have a goal I'd like to achieve. A user communicates with a web browser. The web browser records the user's voice as a WAV file using Recorder.js and sends it to a server running on Google App Engine Standard environment with Python 3.7. The ...

JavaScript tabs function malfunctioning upon page load

I attempted to implement tabs on my website using this example: http://www.w3schools.com/howto/howto_js_tabs.asp Although everything is functioning correctly, the default tab isn't opening as expected. The tab opens, but the header color does not get ...

Unable to attach numerous parameters to the content of the request

I am encountering an issue with my code where I have two classes and need to call two separate models using two store procedures to insert data into both tables. The controller is set up like this: [HttpPost] public IHttpActionResult AddData([FromBody]ILi ...

Sending an array object from Ajax to Django Framework

AJAX Script Explanation: Let's consider the variable arry1D contains values [0,1,2,3,4] $.ajax({ url: "{% url 'form_post' %}", type: "POST", data: { arry1D: arry1D, 'csrfmiddlewaretoken': tk }, ...

Speeding up the loading time of my background images

body { background: url(http://leona-anderson.com/wp-content/uploads/2014/10/finalbackgroundMain.png) fixed; background-size:100% auto; } I have unique background images on each of my sites, but they are large in size and take some time to load due to bein ...

A fresh PHP page escapes from the confines of an iframe and expands to occupy the entire

When calling a new url from inside an iframe, the goal is for the new url to break free from the confines of the iframe and appear full screen. The challenge lies in not having control over the call to the new php file, as it is initiated by a credit card ...