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

查看:219
本文介绍了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部分很简单(使用转换,将改变,包含),我是在何时使用 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天全站免登陆