如何提高requestAnimationFrame的性能?

时间:2018-08-09 16:07:13

标签: javascript animation requestanimationframe

这是我第一次尝试使用rAF制作平滑的动画,我希望获得更多经验丰富的开发人员的一些见解。基本上我有16个具有x,y坐标的元素,并在它们的父容器上移动鼠标时,所有元素都沿相反方向移动了一个设定的量。当我在低端计算机上进行测试时,会遇到一些困难。有什么我不知道的技术可以提高动画效果吗?

(function ($) {
$(document).ready(() => {
const animCont = document.querySelector('.shop-header-container');
const animContWidth = animCont.offsetWidth;
const animContHeight = animCont.offsetHeight;
const leftOffset = animCont.getBoundingClientRect().left;
const topOffset = document.querySelector('#primary').offsetTop;
const animImgs = animCont.querySelectorAll('.elem');
let mouseX = 0;
let mouseY = 0;
let mouseOver = false;
let positions = [
  {
    id: 82,
    start: {
      x: 0.596,
      y: 0.654,
    },
    range: 0.4,
  }
...
]
positions.forEach(el => {
  el.target = {};
  el.current = {};
})
function updateElements(){
  mouseTargetX = (mouseX - leftOffset) / animContWidth;
  mouseTargetY = (mouseY + topOffset) / animContHeight;
  positions.forEach((el,i) => {
    if (mouseOver) {
      el.target.x = ((mouseTargetX - el.start.x) * -el.range + el.start.x ) * animContWidth;
      el.target.y = ((mouseTargetY - el.start.y) * -el.range + el.start.y ) * animContHeight;
    } else {
      el.target.x = el.start.x * animContWidth;
      el.target.y = el.start.y * animContHeight;
    }

    if(!el.current.x) {
      el.current.x = el.target.x;
      el.current.y = el.target.y;
    } else {
      el.current.x = el.current.x + (el.target.x - el.current.x)*0.1;
      el.current.y = el.current.y + (el.target.y - el.current.y)*0.1;
    }

    animImgs[i].style.transform = 'translate3d('+el.current.x+'px,'+el.current.y+'px,0)';
  })
  requestAnimationFrame(updateElements);
}
updateElements();
function animContMouseEnter(e){
  mouseOver = true;
}
function animContMouseLeave(){
  mouseOver = false;
}
function animContMouseOver(e){
  mouseX = e.clientX;
  mouseY = e.clientY;
}
animCont.addEventListener("mousemove",animContMouseOver,false);
animCont.addEventListener("mouseenter",animContMouseEnter,false);
animCont.addEventListener("mouseleave",animContMouseLeave,false);
});
}(jQuery));

这是js代码。

0 个答案:

没有答案