萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 實作氣泡上升特效:物理模擬與滑鼠互動

效果介紹

本範例使用原生 JavaScript 實現「氣泡從水底上升」的視覺特效,結合簡易物理模擬(浮力、阻力、水流擾動)與滑鼠位置互動,展示 DOM 動畫與數學計算的結合應用。

核心架構:面向對象設計

採用建構函數 CObj 封裝單顆氣泡屬性與行為:

function CObj(index, imgElement, width, height) {
  this.obj = document.createElement("img");
  this.obj.src = imgElement.src;
  this.obj.style.position = "absolute";
  this.obj.style.left = "-1000px"; // 初始隱藏於視野外
  document.body.appendChild(this.obj);

  // 物理屬性
  this.x0 = 0;           // 當前 X 座標
  this.y0 = -1000;       // 當前 Y 座標(開始於畫面下方外)
  this.v = 1 + Math.round((80 / height) * Math.random()); // 上升速度(體積越小越快)
  this.p = 1 + Math.round((width / 8) * Math.random());   // 水平擺動幅度
  this.xx = 0; this.yy = 0; // 速度分量
  this.ec = 0;             // 滑鼠影響計數器
  this.w = width; this.h = height;
  this.N = index;          // 隨機重置偏移量
}

物理模擬核心:movbulb() 方法

function movbulb() {
  with (this) {
    // 1. 滑鼠吸引效果:滑鼠靠近時產生引力
    if (ec < 20) {
      if (Math.abs(x0 - xm) < 100 && Math.abs(y0 - ym) < 100) {
        xx = (xm - x0) / 8; // X 方向引力
        yy = (ym - y0) / 8; // Y 方向引力
        ec++;
      }
    }

    // 2. 阻尼衰減:模擬水的阻力
    xx *= 0.99;
    yy *= 0.99;

    // 3. 位置更新
    // 正弦波水平擺動 + 滑鼠引力 X 分量
    x0 = Math.round(x0 + Math.cos(y0 / 15) * p) + xx;
    // 垂直上升 + 滑鼠引力 Y 分量
    y0 += yy - v;

    // 4. 邊界檢測與重生
    if (y0 < -h * 2 || x0 < -w * 2 || x0 > nx + w * 2) {
      // 飛出視窗上方/左側/右側 → 重置到底部隨機位置
      y0 = ny + N + h * 2;
      x0 = nx / 2 - 100 + Math.random() * 100;
      ec = 0; // 重置滑鼠影響計數
    }

    // 5. 更新 DOM
    obj.style.top = (y0 - h) + "px";
    obj.style.left = (x0 - w) + "px";
  }
}

場景初始化與主循環

var object = [];      // 氣泡實例陣列
var nbfm = 60;        // 氣泡總數
var xm = 0, ym = 9999; // 滑鼠座標(初始化為畫面外)
var nx = 0, ny = 0;    // 視窗尺寸

// 視窗縮放同步
function resize() {
  nx = document.body.offsetWidth;
  ny = document.body.offsetHeight;
}
window.onresize = resize;

// 滑鼠追蹤(相容舊版 IE)
document.onmousemove = function(e) {
  e = e || window.event;
  xm = document.body.scrollLeft + (e.x || e.clientX);
  ym = document.body.scrollTop + (e.y || e.clientY);
};

// 主動畫循環(約 60fps)
function run() {
  for (var i in object) object[i].movbulb();
  setTimeout(run, 16); // 遞迴 setTimeout 優於 setInterval:避免積壓
}

// 頁面載入完成後初始化
window.onload = function() {
  var PIC = document.getElementById("bubbles").getElementsByTagName("img");
  resize();
  
  for (var nbf = 0; nbf < nbfm; nbf++) {
    var srcImg = PIC[nbf % PIC.length]; // 循環使用素材圖
    object[nbf] = new CObj(nbf, srcImg, srcImg.width / 2, srcImg.height / 2);
  }
  run();
};

HTML 與 CSS 設置

<style>
  body {
    margin: 0; padding: 0;
    overflow: hidden;        /* 隱藏捲軸 */
    background: #000;        /* 深色背景凸顯氣泡 */
    width: 100%; height: 100%;
    position: absolute; left: 0; top: 0;
    cursor: crosshair;       /* 十字準星游標 */
  }
  #bubbles { visibility: hidden; } /* 素材容器隱藏 */
</style>

<body>
  <div id="bubbles">
    <img src="bubble1.gif">
    <img src="bubble2.gif">
    <img src="bubble3.gif">
    <img src="bubble4.gif">
  </div>
</body>

效能優化建議

優化點說明
使用 Canvas/WebGL大量粒子(>200)時 DOM 操作成為瓶頸,Canvas 繪圖效能優於 DOM
requestAnimationFrame替代 setTimeout(run, 16),瀏覽器優化幀率、背景頁籤自動暫停
Object Pooling重用氣泡實例而非銷毀重建,減少 GC 壓力
CSS will-change為氣泡元素添加 will-change: transform, opacity 開啟 GPU 合成層
減少重排批次讀取佈局屬性、使用 transform: translate3d() 替代 top/left

現代化重寫方向(ES6 Class + Canvas)

class Bubble {
  constructor(canvas, images) {
    this.canvas = canvas;
    this.ctx = canvas.getContext("2d");
    this.img = images[Math.floor(Math.random() * images.length)];
    this.reset();
  }
  
  reset() {
    this.x = Math.random() * this.canvas.width;
    this.y = this.canvas.height + this.img.height;
    this.vy = 1 + Math.random() * 3;
    this.vx = (Math.random() - 0.5) * 0.5;
    this.wobble = Math.random() * Math.PI * 2;
    this.wobbleSpeed = 0.02 + Math.random() * 0.03;
  }
  
  update(mouse) {
    // 滑鼠互動邏輯...
    this.y -= this.vy;
    this.x += Math.sin(this.wobble) * 0.5 + this.vx;
    this.wobble += this.wobbleSpeed;
    
    if (this.y < -this.img.height) this.reset();
  }
  
  draw() {
    this.ctx.drawImage(this.img, this.x, this.y);
  }
}

總結

此範例展示了早期 JavaScript 以 DOM 元素模擬粒子系統的經典寫法,雖然現代開發多改用 Canvas/WebGL,但其面向對象封裝、物理參數隨機化、主循環設計等思想仍具參考價值。理解這些基礎有助於掌握現代動畫庫(如 GSAP、Three.js、PixiJS)的底層原理。

copyright © 萬盛學電腦網 all rights reserved