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
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'));
What your requestAnimationFrame statement evaluates to:
scroll(timestamp, distanceToScroll, secondsToScroll), where timestamp is undefined. It throws an error or returns undefinedwindow.requestAnimationFrame is executed without parameters, thus no callbackPassing 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 callbacktimestamp as first parameterscroll is called with current timestamp, distanceToScroll and secondsToScroll as parameters