背景圖片 (如落葉圖) 以斜向等速平移,營造動態氛圍。原始碼使用 document.body.style.backgroundPosition 週期性更新。

var background = "/edu/img/js/0910/bg.gif";
var speed = 0; // 實際未使用,setTimeout 固定間隔
function moveback(movert, movedn, hPos, vPos, bgImg, repeat) {
// 更新背景圖、repeat 模式
hPos += movert; vPos += movedn;
// 邊界重置邏輯 (超出則歸零)
document.body.style.backgroundPosition = hPos + " " + vPos;
setTimeout(() => moveback(movert, movedn, hPos, vPos, bgImg, repeat), speed);
}
moveback(1, 1, 0, 0, background);
| 問題 | 改進方案 |
|---|---|
| 依賴 body 背景,無法獨立控制圖層 | 改用固定定位 <div class="bg-layer"> + transform: translate3d() |
| setTimeout 非最佳幀率控制 | 改用 requestAnimationFrame 配合 performance.now() 計算位移 |
| 單一圖片重複感強 | 多圖層差速滾動 (Parallax) 增加立體感 |
| 無暫停/銷毀機制 | 封裝為 Class,提供 start()/stop()/destroy() |
class ParallaxLeaves {
constructor(layers = 3, imgSrc = 'leaves.png') {
this.layers = Array.from({length: layers}, (_,i) => {
const el = document.createElement('div');
el.style.cssText = `position:fixed;top:0;left:0;width:100%;height:100%;
background:url(${imgSrc}) repeat;z-index:-${i+1};will-change:transform;`;
document.body.appendChild(el);
return {el, speed: 0.2 + i*0.15, x: 0, y: 0};
});
this.rafId = null;
}
animate(ts) {
this.layers.forEach(l => {
l.x -= l.speed; l.y += l.speed * 0.5;
l.el.style.transform = `translate3d(${l.x}px, ${l.y}px, 0)`;
if (l.x < -w) l.x = 0; // 簡易循環
});
this.rafId = requestAnimationFrame(this.animate.bind(this));
}
start() { this.animate(0); }
stop() { cancelAnimationFrame(this.rafId); }
}
new ParallaxLeaves(4, 'leaves.png').start();
will-change: transform 提升合成層document.visibilityState 暫停動畫