[英]Improving performance of parallax effect triggered by mousemove event
我在此网站的启发下在这里制作了视差效果。 当前,它侦听mousemove事件,并使用CSS变换进行视差。 我还使用lodash的节流功能,以使事件不会被频繁触发。
伪代码:
let parallax = (e) => {
// calculate deltas of mouse x and y from the midpoint
// multiplier = 0.01
// for every parallax image
// translate image (multiplier * dx, multiplier * dy)
// multiplier *= 0.8
}
document.addEventListener('mousemove', _.throttle(parallax, 10));
但是,这种方法的性能仍然不是最佳的,我想知道如何改进它?
增加油门时间会导致非常明显的滞后。 我也一直在研究使用canvas和requestAnimationFrame,但是我不确定它的性能如何与使用CSS相提并论。
我已重做视差效果以使用3d定位和透视图更改。
透视图更改模拟更改您的观点。
对象应具有z位置,使它们相对或多或少地移动,就像在现实世界中一样
现在,它应该运行得更加高效,因为所有这些都可以在单个属性更改中处理并在GPU上执行
let bg = document.querySelector('.background'); let rect = bg.getBoundingClientRect(); let midX = rect.left + rect.width / 2; let midY = rect.top + rect.height / 2; let parallax = (e) => { let dx = e.clientX - midX; let dy = e.clientY - midY; let mult = -0.5; let perspective = `${dx * mult}px ${dy * mult}px`; bg.style.perspectiveOrigin = perspective; } document.addEventListener("mousemove", parallax);
body { width: 100%; height: 100%; overflow: hidden; } .background { background-color: whitesmoke; width: 400px; height: 400px; position: absolute; top: 0; bottom: 0; left: 0; right: 0; margin: auto; perspective: 500px; transform-style: preserve-3d; } img { position: absolute; top: 0; bottom: 0; left: 0; right: 0; width: 200px; margin: auto; } .one { top: 100px; width: 300px; transform: translateZ(1px); } .two { top: 0px; width: 300px; transform: translateZ(100px); } .text { line-height: 400px; width: 200px; position: relative; z-index: 1000; text-align: center; color: red; transform-style: preserve-3d; transform: translateZ(200px); }
<div class="background" style="perspective-origin: -18.025px 14.15px;"> <h1 class="plax text">Hello.</h1> <img class="plax two" src="http://www.etiennegodiard.com/wp-content/uploads/2017/06/YokaVendredi-copie-min.png"> <img class="plax one" src="http://www.etiennegodiard.com/wp-content/uploads/2017/04/Yokaombre5.png"> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.