Adding Additional Arguments To A Function Called Back By RequestAnimationFrame
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 is how
Solution 1:
What your requestAnimationFrame statement evaluates to:
scroll(timestamp, distanceToScroll, secondsToScroll), where timestamp is undefined. It throws an error or returns undefinedwindow.requestAnimationFrameis 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.requestAnimationFrameis called with anonymous function as callback- anonymous function is called with
timestampas first parameter scrollis called with currenttimestamp,distanceToScrollandsecondsToScrollas parameters
Solution 2:
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'));
Post a Comment for "Adding Additional Arguments To A Function Called Back By RequestAnimationFrame"