简体   繁体   中英

requestAnimationFrame trigger if element is on screen

For my scrolling website I want use requestAnimationFrame to create an animation. The requestAnimationFrame must be triggered if the element is on screen by scrolling. I have an issue with this. The requestAnimationFrame runs only if I refresh the page and the element is on screen. If I load the page and I scroll down the requestAnimationFrame is not running.

Below my code

window.addEventListener('scroll', ()=>{
    var contentPosition = element.getBoundingClientRect().top;
var screenPosition = window.innerHeight;
if(contentPosition < screenPosition){
    requestAnimationFrame(run);
}
                    
});
var start_time = new Date().getTime();
function run(){
    var time = new Date().getTime() - start_time;
var result = easeInOutQuart(time, from, to - from, duration);
if(time <= duration){
    requestAnimationFrame(run);
    element.style.left = result+"px";
};
}

function easeInOutQuart(t, b, c, d){
    if((t /= d / 2) < 1){
        return c / 2 * t * t * t * t + b;
}else{
    return -c / 2 * ((t -= 2) * t * t * t - 2) + b;
}
}

I tested my code with a console.log an this works fine

window.addEventListener('scroll', ()=>{
    var contentPosition = element.getBoundingClientRect().top;
var screenPosition = window.innerHeight;
if(contentPosition < screenPosition){
    //requestAnimationFrame(run);
        console.log('trigger');
}
                    
});

You're defining start_time (possibly) long before run is called. So when run is finally called, it will think it's already animating for more than the expected duration, and do nothing.

Move

start_time = new Date().getTime();

in the

if(contentPosition < screenPosition){

block.

However you'll face a new problem: If the user keeps scrolling during the animation, the timer will get reset and the animation will start again, with possibly many calls in parallel.
To avoid that you'd need to remove the event listener in that same block (either use removeEventListener() or an AbortSignal ).

But anyway, you'd be better using an IntersectionObserver rather than listening to all the scroll events anyway.

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