简体   繁体   中英

Limit scroll ability on HTML5 canvas elements

I've got a series of rectangles drawn on a canvas and use a scroll event listener to move the boxes up and down.

I'm trying to add in some validation so that the boxes cannot be scrolled past a certain point.

Due to the acceleration, the scroll values don't always increment by 1, so when scrolling quickly, sometimes my validation kicks in too early.

Any ideas how to solve this?

So in my event listener I have:

lScroll += e.deltaY;

if (lScroll > 0) {
    canScroll = false;
    lScroll = 0;
} else {
    canScroll = true;
}

https://jsfiddle.net/kr85k3us/3/

Please check if this is working for you: https://jsfiddle.net/kr85k3us/4/

I tested it and it should work, but perhaps you can move your mousewheel faster :)

if (!canScroll && lScroll == 0) {
    var first = Object.keys(boxes)[0];

    if (boxes[first]['y'] < 10) {
        var delta = 10 - boxes[first]['y'];
        Object.keys(boxes).forEach(function(k){ boxes[k]['y'] += delta; });
    }
}

This is the piece of code I added. If you can't scroll and lScroll is 0, it means that we reached the top. Next, I check if the first box is where it should be. If not (ie boxes[first]['y'] < 10 ) then it adjusts all the boxes' y position.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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