2017-07-16 9 views
0

this websiteによって触発された視差効果hereを作成しました。現在、mousemoveイベントをリッスンし、視差を行うためにCSS変換を使用します。また、ロダッシュのスロットル機能を使用して、イベントが頻繁に発せられることもありません。mousemoveイベントによって引き起こされる視差効果の改善

擬似コード:

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)); 

しかし、この性能は、まだ最適ではないと私はそれを改善するために何ができるか不思議でしたか?

スロットル時間を長くすると、非常に明白な遅れが生じます。キャンバスとrequestAnimationFrameを使用することも検討していましたが、そのパフォーマンスがCSSを使用してどのようにスタックされているかわかりません。

答えて

1

私は視差を3d位置付けと視点の変更を使用してやり直しました。

視点の変更は、視点の変更をシミュレートします。

オブジェクトは、彼らがちょうど現実の世界のように、多かれ少なかれ、相対的に移動可能AZポジションを持っている必要があり

このすべてが単一のプロパティの変更に扱われ、上で実行されているのでそれは、今、はるかに効率的に実行する必要があり

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>

+0

はちょっと@valsは、これを行うために時間を割いてくれてありがとう! –

関連する問題