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

What category does React.js fall under - library or framework?

Hey there! I've noticed that sometimes people refer to React JS as a library, while others call it a framework. Can you shed some light on which term is more accurate? ...

Exploring advanced routing concepts in Angular 2

I have a challenge in setting up routing in angular 2 with the following scenario home.component: @RouteConfig([ { path: '/', name: 'Home', component: HomeComponent }, { ...

Instructions on adding an activity indicator in a centered box with a loader inside

I'm currently working on integrating an Activity Indicator into my Vue Native App, but I've been facing some issues as it doesn't seem to be displaying the Activity Indicator properly. Here is the code snippet I've tried: <Absolute ...

Prevent animations on child elements with Vue.js

I am dealing with a scenario where I want to remove the fade transition on a child div within a <transition> component. The reason for nesting it is to prevent layout flickering, which can be demonstrated in a fiddle if necessary. In the fiddle belo ...

Executing Knex promises sequentially within a for loop

I have recently started to dive into Node and asynchronous coding, but I am struggling with a fundamental concept. I am trying to seed a database using knex, reading data from a CSV file and iterating through the rows in a for loop. In each iteration, I ne ...

Dealing with issues escaping unicode characters in JavaScript

Whenever I need to load data from an external file based on a specific event, I make use of the following jQuery code: $("#container").load("/include/data.php?name=" + escape(name)); An issue arises when the JavaScript variable "name" contains Unicode ch ...

The CSS is not displaying correctly on Safari and Chrome browsers in Mac OS

I'm having trouble with CSS not loading properly on Apple devices for a website I made. Despite maintaining all media query statements and style sheets separately, the display is not correct in MAC OS safari and chrome. However, everything looks fine ...

Tips for troubleshooting the error "Cannot locate module mp3 file or its associated type declarations"

Seeking guidance on resolving the issue with finding module './audio/audio1.mp3' or its type declarations. I have already attempted using require('./audio/audio1.mp3'), but continue to encounter an error. ...

Why is the current Menu Item highlight feature not functioning properly?

Why isn't the highlight current Menu Item feature working? I've checked my code, but it doesn't seem to be functioning as expected. Could you lend me a hand? Html: <section id="menu-container"> <div id="bar"><img src="b ...

How to override the styling of a parent element in CSS

I'm encountering an issue with my website's sidebar. I've set the background color to yellow for elements with the currentPage class. This works fine for the 'Home' tab, but when I try to do the same for a nested tab like 'tag ...

Tips for updating multiple fields in Prisma ORM

Is there a way to upsert multiple fields in Prisma ORM using just one query? I'm looking for a solution that allows me to upsert all fields at once, without having to do it individually. Is this possible? ...

The Facebook SDK fails to activate in Internet Explorer

I am currently working on implementing a Facebook login using the JavaScript SDK. Everything is functioning correctly in most browsers, but I am experiencing issues with certain versions of Internet Explorer. The login functionality is not working on my l ...

Using jQuery and regex to only allow alphanumeric characters, excluding symbols and spaces

Seeking advice, I am using a jquery function called alphanumers var alphanumers = /^[a-zA-Z0-9- ]*$/; which currently does not allow all symbols. However, I now wish to disallow the space character as well. Any suggestions? ...

Setting model value in Angular 2 and 4 from loop index

Is it possible to assign a model value from the current loop index? I've tried, but it doesn't seem to be working. Any suggestions on how to achieve this? Check out this link for my code <p *ngFor="let person of peoples; let i = index;"& ...

The animation in Rive feels sluggish when navigating to a page with animation in Blazor WASM, despite implementing dispose methods

After attempting to display river animation on the index page using Blazor WASM (basic template), I encountered some performance issues. When navigating back and forth between the Counter page and the index page, I noticed that after around 20 clicks, the ...

Steps for referencing an autogenerated id in a Firestore collection

I need assistance updating a 'progress' field in a document with an autogenerated ID (using Firestore) every time the progress button is clicked. https://i.stack.imgur.com/hZieN.png Despite my attempts, nothing seems to work. Here is the method ...

Customizing React-Data-Grid styles using Material-UI in a React application

Imagine a scenario where we have a file containing themes: themes.js: import {createMuiTheme} from "@material-ui/core/styles"; export const myTheme = createMuiTheme({ palette: { text: { color: "#545F66", }, }, }); In ...

Ensuring uniform sizing of anchor text using jQuery

My goal is to creatively adjust the font size of anchor text within a paragraph, making it appear as though the text is moving towards and away from the viewer without affecting the surrounding paragraph text. Currently, I am encountering an issue where th ...

Even after unsubscribing with mqtt.js, the old listener continues to receive messages

Currently, I am utilizing mqtt.js to receive websocket data from an MQTT server. The subscription process is functioning properly, but the challenge lies in changing the topic dynamically by modifying the websocket configuration. The issue arises when, eve ...

Utilizing a callback function to update the value of a variable that is declared outside of the getJSON function

I'm currently facing an issue with this function I have. function customCheck(username){ var result = "normal"; $.getJSON('https://api.twitch.tv/kraken/streams/' + username, function(data){ if(data.stream == null) re ...