简体   繁体   English

禁用 html5 画布点击事件

[英]Disable html5 canvas click events

I have a canvas element, and in the canvas if you click a button it opens a div modal.我有一个画布元素,在画布中,如果您单击一个按钮,它会打开一个div模式。 The modal then has some buttons on it, and if you click on one of the buttons and it is also above a button in the canvas, the canvas button also gets clicked.然后模态上有一些按钮,如果您单击其中一个按钮并且它也在画布中的按钮上方,则画布按钮也会被单击。

I would like to disable the canvas, but I can't seem to do so.我想禁用画布,但我似乎无法这样做。 I have a tried applying css styles to the canvas like so:我尝试将 css 样式应用到canvas如下所示:

pointer-events: none

But the canvas still accepts the clicks.但是画布仍然接受点击。 Is there any way for me to disable the canvas so that I can click on the modal without it affecting the canvas?有什么方法可以禁用画布,以便我可以单击模态而不影响画布?

The canvas contains a game, and the game isn't always the same, so I don't have access to the canvas' code to disable the buttons in the canvas.画布包含一个游戏,游戏并不总是相同的,所以我无法访问画布的代码来禁用画布中的按钮。

You can simply make a handler such as您可以简单地制作一个处理程序,例如

const c = document.querySelector("#myCanvas")
c.addEventListener('click', e => {
    if (c.classList.contains('disabled')) {return}
    // Do not perform default action, stop bubbling the event
    e.preventDefault();e.stopPropagation()

    // Mark event as invalid for older browsers
    return false
})

Edit: More Conclusive solution编辑:更具决定性的解决方案

 .canvas-wrapper {position:relative} .canvas-wrapper:after {content:'';position:absolute;z-index:999;top:0;left:0;width:100%;height:100%;cursor: not-allowed; pointer-events: none}
 <div class='canvas-wrapper'> <canvas></canvas> </div>

This creates a faux blocking element atop your canvas element, this way it gathers all click events before they can even hit the canvas ( since the canvas is under this element )这会在您的canvas元素之上创建一个人造阻塞元素,这样它会在所有点击事件甚至可以击中canvas之前收集所有点击事件(因为画布在这个元素下

Event Propagation - https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation事件传播 - https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation

In the event handler for the button click, stop the propagation of the event.在按钮单击的事件处理程序中,停止事件的传播。

First, you set it up like this:首先,你这样设置:

<div class='your-canvas-wrapper'>
<canvas>
...
</canvas>
</div>

If you want to disable on page load.如果您想在页面加载时禁用。

.your-canvas-wrapper {
    cursor: not-allowed;
    pointer-events: none;
}

If you want to disable after page load, you can do this...如果你想在页面加载后禁用,你可以这样做......

$(".your-canvas-wrapper").css("cursor", "not-allowed");
$(".your-canvas-wrapper").css("pointer-events", "none");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM