Reputation: 61
Say I have below
const canvas1 = document.createElement("canvas");
const canvas2 = document.createElement("canvas");
canvas1.width = window.innerWidth;
canvas2.width = window.innerWidth;
canvas1.height = window.innerHeight;
canvas1.height = window.innerHeight;
canvas1.addEventListener('click', onClickCanvas1);
canvas2.addEventListener('click', onClickCanvas2);
Because both canvases are located exactly the same location, the click event can only be listened to canvas1 or canvas2 (either canvas with more z-index value).
Is there any way to get both canvases to listen to the same mouse event?
Upvotes: 1
Views: 449
Reputation: 205979
Since your canvases are overlapping with a higher z-index, simply assign the "click" to a common parent element
someElementWrapper.addEventListener("click", (ev) => {
const bcr = ev.currentTarget.getBoundingClientRect();
const x = ev.clientX - bcr.left;
const y = ev.clientY - bcr.top;
// here pass the x and y coordinates in your app logic. For example:
updateAllCanvases(x, y);
});
Alternatively, add CSS pointer-events: none;
to your own canvas.
<div id="wrapper"> <!-- I LISTEN TO MOUSE/TOUCH EVENTS! YEY -->
<canvas id="canvas-others"></canvas> <!-- HAS ITS OWN EVENTS -->
<canvas id="canvas-mine"></canvas> <!-- HAS POINTER-EVENTS: NONE -->
</div>
Or simply - assign events directly to the 3rd party canvas.
Upvotes: 2