簡體   English   中英

改善mousemove事件觸發的視差效果的性能

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM