最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Prevent window scrolling with canvas - Stack Overflow

programmeradmin8浏览0评论

I'm trying to prevent the window from scrolling when the mouse wheel is used while over a canvas. I tried disabling it like this:

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

And several other ways but nothing works see:

/

Make the browser window small so there is a scroll bar, then mouse wheel over the canvas and it will make the window scroll. How can I let the canvas receive the wheel message but prevent the window from scrolling?

I'm using jquery (not shown here).

I'm trying to prevent the window from scrolling when the mouse wheel is used while over a canvas. I tried disabling it like this:

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

And several other ways but nothing works see:

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

Make the browser window small so there is a scroll bar, then mouse wheel over the canvas and it will make the window scroll. How can I let the canvas receive the wheel message but prevent the window from scrolling?

I'm using jquery (not shown here).

Share Improve this question asked Apr 23, 2015 at 18:39 PhilipPhilip 1,9114 gold badges26 silver badges42 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 14

You can use the wheel event. You may need to use mousewheel instead for other browsers than Firefox -- but please note that the mousewheel event has since been deprecated in favor of WheelEvent.

Vanilla JavaScript version

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 version

$("#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>

This worked quite well for me

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 });
发布评论

评论列表(0)

  1. 暂无评论