萬盛學電腦網

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

HTML5 Canvas 粒子進度條:打造極具視覺衝擊力的載入動畫

傳統進度條枯燥乏味?利用 Canvas 粒子系統打造極具科技感的動態載入效果:進度條推進伴隨彩色粒子噴發、重力下落、漸變消失。本文完整拆解這個視覺效果的核心架構與實現細節。

效果特性

  • 水平進度條:HSL 色相隨進度從 0°→120°(紅→綠)漸變
  • 粒子系統:進度推進處持續噴發粒子,受重力下落、透明度漸變消失
  • requestAnimationFrame 驅動 60fps 流暢動畫
  • 輕量無依賴,核心邏輯 < 150 行

核心架構

class LightLoader {
  constructor(canvas, width, height) {
    this.ctx = canvas.getContext('2d');
    this.cw = width; this.ch = height;
    // 進度條配置
    this.loaded = 0;
    this.loaderSpeed = 0.6;      // 進度增量/幀
    this.loaderWidth = 310;
    this.loaderHeight = 10;
    this.loader = { x: (width-310)/2, y: (height-10)/2 };
    // 粒子配置
    this.particles = [];
    this.particleLift = 180;     // 初始向上速度範圍
    this.hueStart = 0; this.hueEnd = 120; // 色相範圍
    this.gravity = 0.15;
    this.particleRate = 4;       // 每幀生成粒子數
  }

  // 主循環
  loop() {
    const tick = () => {
      requestAnimationFrame(tick);
      this.clearCanvas();
      this.createParticles();
      this.updateLoader();
      this.updateParticles();
      this.renderLoader();
      this.renderParticles();
    };
    tick();
  }
  // ... 具體方法見下文
}

關鍵模塊實現

進度條更新與渲染


updateLoader() {
  this.loaded = (this.loaded + this.loaderSpeed) % 100; // 循環
}

renderLoader() {
  const {ctx, loader, loaderWidth, loaderHeight, loaded, hueStart, hueEnd} = this;
  // 背景槽
  ctx.fillStyle = '#000';
  ctx.fillRect(loader.x, loader.y, loaderWidth, loaderHeight);
  // 進度填充(漸變色相)
  const hue = hueStart + (loaded/100) * (hueEnd - hueStart);
  const w = (loaded/100) * loaderWidth;
  ctx.fillStyle = `hsla(${hue}, 100%, 40%, 1)`;
  ctx.fillRect(loader.x, loader.y, w, loaderHeight);
  // 高光
  ctx.fillStyle = '#222';
  ctx.fillRect(loader.x, loader.y, w, loaderHeight/2);
}

粒子系統


createParticles() {
  for (let i = 0; i < this.particleRate; i++) {
    this.particles.push(new this.Particle());
  }
}

Particle() {
  // 生成位置:進度條前端附近
  this.x = this.loader.x + (this.loaded/100)*this.loaderWidth + rand(-1,1);
  this.y = this.ch/2 + rand(0, this.loaderHeight) - this.loaderHeight/2;
  // 隨機速度
  this.vx = (rand(0,4)-2)/100;
  this.vy = (rand(0, this.particleLift) - this.particleLift*2)/100;
  this.width = this.height = rand(1,4)/2;
  this.hue = this.hue; // 當前進度色相
}

update(i) {
  this.vx += (rand(0,6)-3)/100; // 水平擴散
  this.vy += this.gravity;      // 重力
  this.x += this.vx;
  this.y += this.vy;
  if (this.y > this.ch) this.particles.splice(i, 1); // 超出移除
}

render() {
  ctx.fillStyle = `hsla(${this.hue}, 100%, ${rand(50,70)}%, ${rand(20,100)/100})`;
  ctx.fillRect(this.x, this.y, this.width, this.height);
}

Canvas 清屏與混合模式


clearCanvas() {
  this.ctx.globalCompositeOperation = 'source-over';
  this.ctx.clearRect(0, 0, this.cw, this.ch);
  this.ctx.globalCompositeOperation = 'lighter'; // 疊加發光效果
}

lighter 模式讓粒子重疊處顏色相加,營造發光感。

requestAnimationFrame 兼容性封裝


var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
  window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
  window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] 
    || window[vendors[x] + 'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame) {
  window.requestAnimationFrame = (cb) => {
    var curr = Date.now();
    var delay = Math.max(0, 16 - (curr - lastTime));
    lastTime = curr + delay;
    return setTimeout(() => cb(curr + delay), delay);
  };
}
if (!window.cancelAnimationFrame) {
  window.cancelAnimationFrame = (id) => clearTimeout(id);
}

啟動入口


function isCanvasSupported() {
  var elem = document.createElement('canvas');
  return !!(elem.getContext && elem.getContext('2d'));
}

if (isCanvasSupported()) {
  var c = document.createElement('canvas');
  c.width = 400; c.height = 100;
  document.body.appendChild(c);
  var loader = new LightLoader(c, c.width, c.height);
  setupRAF(); // 兼容性封裝
  loader.loop();
}

擴展與定製方向

  • 進度驅動源:接入真實資源加載進度(xhr.onprogress、fetch + ReadableStream)
  • 粒子形狀:矩形 → 圓形(arc)、圖片、文字、自定義 Path2D
  • 物理模擬:添加風力、渦流、碰撞、生命周期
  • 主題皮膚:配置色相範圍、粒子大小、重力、發射率
  • WebGL 版本:萬級粒子、GPU 粒子系統、Shader 材質

性能優化提示

  • 粒子對象池復用,避免頻繁 GC
  • 離屏 Canvas 緩存靜態背景
  • globalCompositeOperation 狀態變更最小化
  • 大量粒子考慮 WebGL / WebGPU / OffscreenCanvas + Worker

這個粒子進度條展示了 Canvas 程序化動畫的迷人魅力:簡單的物理規則 + 色彩理論 + 高頻循環 = 豐富的涌現視覺效果。掌握此模式,可快速構建載入動畫、數據可視化過渡、遊戲特效等場景。

copyright © 萬盛學電腦網 all rights reserved