前言
之前所做的方舟官網的輪播效果還原,一邊探索一邊製作。講老實,最終的效果我覺得有點勉強。我一直以為視差效果是最難,做到後面發覺,輪播的效果才是最麻煩的。
視差
之前所做的方舟官網的輪播效果還原,視差效果那裏是最容易實現,使用 JS 變更 CSS 的 transform
屬性就能搞掂。值得一提的是視差過後是有個平滑結束的效果,可以透過 requestAnimationFrame() 方法裏面每次記錄遊標上一刻位置,再透過公式每一格計算將要移動的位置。
requestAnimationFrame()
這裏意思是要求瀏覽器繪製一格動畫,如果想要在下次重繪時產生另一個動畫,這個回呼函數內必須自行呼叫requestAnimationFrame()
。
寫法參考了以下的codepen案例,由於都是錯位跟蹤,遊標的跟蹤效果可以抽象成輪播圖的視差錯位移動。
See the Pen
smooth mouse move follow by Nano (@nanonansen)
on CodePen.
以下放出的是我的代碼:
const mouse = { x: 0, y: 0 } // 遊標位置
const pos = { x: 0, y: 0 } // 跟蹤到達位置
document
.querySelector('body')
.addEventListener('mousemove', ({ x, y }) => {
mouse.x = x
mouse.y = y
})
requestAnimationFrame(function movement() {
const easting = 10 // 用於調整持續時間
pos.x += (mouse.x - pos.x) / easting
pos.y += (mouse.y - pos.y) / easting
const xValue = calcValue(pos.x, window.innerWidth)
const yValue = calcValue(pos.y, window.innerHeight)
// 透過 translate3d 調整圖像上下左右移動,rotateX Y 調整上下左右旋轉
document.querySelector(
'#media-layer-view'
).style.transform = `translate3d(${xValue}px, ${yValue}px, 0) rotateX(${-yValue}deg) rotateY(${xValue}deg)`
document.querySelector('#media-layer-front').style.transform = `translate3d(${
xValue * 7.7
}px, ${yValue * 3}px, 50px) rotateX(${-yValue}deg) rotateY(${
xValue
}deg)`
requestAnimationFrame(movement)
})
function calcValue(a, b) {
const range = 20 // 移動幅度,這裏是影響 translate3d 與 rotateX Y 的幅度
return (a / b) * range - range / 2
}
粒子效果
粒子效果用到了particles.js
這個JS函數庫,原版的官網輪播的後面還有粒子矩形與黃色的多邊形運動動畫效果,但是我能力不足,不清楚如何實現。
輪播圖
這部份寫得很亂,我也不知道如何講起= =
發佈留言