60fps:如何正确使用 requestAnimationFrame? [英] 60fps: How to use requestAnimationFrame the right way?

查看:23
本文介绍了60fps:如何正确使用 requestAnimationFrame?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的网站上,相关内容框在可见时应以动画形式显示到视口中.

On my website, a related content box should be animated into the viewport when it gets visible.

我试图通过 CSS 和 JavaScript 使我的动画尽可能高效,以免对滚动性能产生负面影响.

I’m trying to make my animation as efficient as possible through CSS and JavaScript, so that it doesn’t affects scroll performance negatively.

虽然 CSS 部分很简单(使用 transform、will-change、contain),但我在何时使用 window.requestAnimationFrame 上有点挣扎.

While the CSS part was simple (using transform, will-change, contain), I’m struggling a bit with when to use window.requestAnimationFrame.

我应该仅在将类添加到元素时使用它,还是在调用函数 isScrolledIntoView 或什至在 isScrolledIntoView 中,测量元素位置时使用它?

Should I use it only when the class is added to the element or also when the function isScrolledIntoView is called or even inside isScrolledIntoView, when the elements position is measured?

var percentVisible = 0.25;
window.addEventListener('scroll', function(){
relatedContent(related, percentVisible);
}
)

function relatedContent(r, pV){
    window.requestAnimationFrame(function() {
        if(isScrolledIntoView(r, pV)){
            window.requestAnimationFrame(function(){
                r.classList.add("visible");
             }, r)
        }
    }, r)
}

function isScrolledIntoView(el, percentV) {
var elemTop, elemBottom, elemHeight, overhang, isVisible;
/*window.requestAnimationFrame(
function(){*/
elemTop = el.getBoundingClientRect().top;
elemBottom = el.getBoundingClientRect().bottom;
elemHeight = el.getBoundingClientRect().height;
/*}
);*/
overhang = elemHeight * (1 - percentV);

isVisible = (elemTop >= -overhang) && (elemBottom <= window.innerHeight + overhang);
return isVisible;
}

推荐答案

requestAnimationFrame 返回一个非零 long 可用于取消您的请求,因此您无需编写自己的油门实现,而是可以使用以下更简单的方法来防止多个处理程序堆积:

requestAnimationFrame returns a non-zero long that can be used to cancel your request, so instead of writing your own throttle implementation, you can use the following simpler approach to prevent multiple handlers stacking up:

let currentRequest;
document.addEventListener('scroll', function () {
  cancelAnimationFrame(currentRequest);
  currentRequest = requestAnimationFrame(handleScroll);
});

这篇关于60fps:如何正确使用 requestAnimationFrame?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆