防止 window 使用 canvas 滚动

Prevent window scrolling with canvas

我试图阻止 window 在 canvas 上使用鼠标滚轮时滚动。我试过像这样禁用它:

document.getElementById( "canvasId" ).onmousedown = function(event){
    event.preventDefault();
};

还有其他几种方法,但都不起作用,请参阅:

http://jsfiddle.net/MZ9Xm/1/

将浏览器 window 缩小以便有一个滚动条,然后将鼠标滚到 canvas 上,这将使 window 滚动。如何让 canvas 接收滚轮消息但阻止 window 滚动?

我正在使用 jquery(此处未显示)。

您可以使用 wheel 事件。对于 other browsers,您可能需要使用 mousewheel 而不是 Firefox -- 但请注意,mousewheel 事件已被弃用,取而代之的是 WheelEvent.

原版 JavaScript 版本

document.getElementById( "canvasId" ).onwheel = function(event){
    event.preventDefault();
};

document.getElementById( "canvasId" ).onmousewheel = function(event){
    event.preventDefault();
};
html, body {height:200%} canvas {border:4px solid red}
<canvas id="canvasId"></canvas>

jQuery版本

$("#canvasId").bind("wheel mousewheel", function(e) {e.preventDefault()});
html, body {height:200%} canvas {border:4px solid red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvasId"></canvas>

这对我来说效果很好

document.addEventListener("mousewheel", (e)=>{
    if(e.target === htmlCanvasRef) {
        e.preventDefault()
        canvasApp.zoom(/*do smth with e*/)
        console.log('not scrolling')
    } else {
        console.log('scrolling')
    }
}, { passive: false });