Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 935
Adam Lobo Avatar asked Oct 19 '22 09:10

Adam Lobo


1 Answers

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 (i.e. boxes[first]['y'] < 10) then it adjusts all the boxes' y position.

like image 144
TGO Avatar answered Nov 02 '22 08:11

TGO