Adding additional arguments to a function called back by requestAnimationFrame

前端 未结 2 805
情话喂你
情话喂你 2021-01-05 07:50

I am looking to create a function that scrolls an image element x pixels over y time on an HTML5 canvas, using requestAnimationFrame and delta time. What I can\'t figure out

相关标签:
2条回答
  • 2021-01-05 08:14

    Pure JavaScript

    function scrollIntoViewSmooth(elem) {
        var move = elem.offsetTop - (elem.offsetTop - elem.parentElement.scrollTop) * 0.25;
    
        if (Math.abs(elem.offsetTop - move) <= 2) {
            elem.parentElement.scrollTop = elem.offsetTop;
        } else {
            elem.parentElement.scrollTop = move;
            setTimeout(scrollIntoViewSmooth, 33, elem);
        }
    }
    

    Example

    scrollIntoViewSmooth(document.getElementById('stuff'));
    
    0 讨论(0)
  • 2021-01-05 08:26

    What your requestAnimationFrame statement evaluates to:

    • scroll(timestamp, distanceToScroll, secondsToScroll), where timestamp is undefined. It throws an error or returns undefined
    • window.requestAnimationFrame is executed without parameters, thus no callback

    Passing an anonymous function that calls scroll with the desired parameters should do the trick:

    requestAnimationFrame(function(timestamp) {
        scroll(timestamp, distanceToScroll, secondsToScroll));
    });
    

    What this evaluates to:

    • window.requestAnimationFrame is called with anonymous function as callback
    • anonymous function is called with timestamp as first parameter
    • scroll is called with current timestamp, distanceToScroll and secondsToScroll as parameters
    0 讨论(0)
提交回复
热议问题