[英]How do I share mouse events between multiple canvases?
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).因为两个画布位于完全相同的位置,所以点击事件只能监听到 canvas1 或 canvas2(canvas 具有更多的 z-index 值)。
Is there any way to get both canvases to listen to the same mouse event?有没有办法让两个画布都听同一个鼠标事件?
Since your canvases are overlapping with a higher z-index, simply assign the "click" to a common parent element由于您的画布与更高的 z-index 重叠,只需将“点击”分配给一个公共父元素
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;
或者,添加 CSS pointer-events: none;
to your own canvas.到您自己的 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.或者简单地说 - 将事件直接分配给第 3 方 canvas。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.