萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML5 教學

HTML 斜向移動落葉背景特效代碼實現與優化

效果描述

背景圖片 (如落葉圖) 以斜向等速平移,營造動態氛圍。原始碼使用 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()

現代化實現範例 (Parallax 落葉)

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 提升合成層
  • 圖片壓縮至 <50KB、使用 WebP 格式
  • 頁面不可見時 document.visibilityState 暫停動畫
copyright © 萬盛學電腦網 all rights reserved