萬盛學電腦網

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

JavaScript 實現靜態圖片粒子動畫效果:Canvas 像素數據可視化

前言

將靜態圖片轉化為動態粒子動畫是創意前端的經典案例。核心原理:使用 Canvas getImageData() 獲取像素數據,提取非透明像素點,將每個像素作為粒子進行物理模擬動畫。本文解析完整實現邏輯並提供封裝庫設計思路。

一、核心原理流程

  1. 圖片加載:創建 Image 對象加載圖片,等待 onload
  2. 像素採樣:將圖片繪製到離屏 Canvas,調用 getImageData() 獲取 RGBA 數據
  3. 粒子提取:遍歷像素數據,過濾透明度 > 閾值的像素,記錄位置、顏色創建粒子對象
  4. 物理模擬:賦予粒子速度、加速度、阻尼等屬性,幀循環更新位置
  5. 渲染繪製:每幀清空 Canvas,繪製所有粒子 (圓點/方塊/圖片)

二、HTML 結構與調用


<!DOCTYPE html>
<html>
<head>
    <title>Particle Image Animation</title>
    <meta charset="utf-8" />
    <style>
        #logo { 
            margin: 20px; 
            width: 160px; 
            height: 48px; 
            background: url('./images/logo.png'); 
        }
    </style>
    <script src="ParticleImage.js"></script>
    <script>
        window.onload = function() {
            // 容器ID、圖片路徑、速度模式
            ParticleImage.create("logo", "./images/logo.png", "fast");
        };
    </script>
</head>
<body>
    <div id="logo"></div>
</body>
</html>

三、核心庫實現 (ParticleImage.js 關鍵邏輯)


var ParticleImage = (function() {
    // 配置常量
    const CONFIG = {
        particleRadius: 1.5,
        density: 6,           // 採樣間隔,越小越密集
        speedModes: {
            slow: { friction: 0.98, gravity: 0.1 },
            normal: { friction: 0.95, gravity: 0.3 },
            fast: { friction: 0.9, gravity: 0.5 }
        }
    };

    var canvas, ctx, particles = [], imgData = null;
    var animationId, speedMode = 'normal';

    // 1. 初始化 Canvas
    function initCanvas(containerId) {
        const container = document.getElementById(containerId);
        canvas = document.createElement('canvas');
        canvas.width = container.offsetWidth;
        canvas.height = container.offsetHeight;
        container.innerHTML = '';
        container.appendChild(canvas);
        ctx = canvas.getContext('2d');
    }

    // 2. 載入圖片並提取像素
    function loadImage(src, callback) {
        const img = new Image();
        img.crossOrigin = 'anonymous'; // 支持跨域圖片
        img.onload = function() {
            // 創建離屏 Canvas 繪製圖片獲取像素
            const tempCanvas = document.createElement('canvas');
            tempCanvas.width = img.width;
            tempCanvas.height = img.height;
            const tempCtx = tempCanvas.getContext('2d');
            tempCtx.drawImage(img, 0, 0);
            
            try {
                imgData = tempCtx.getImageData(0, 0, img.width, img.height);
                callback();
            } catch (e) {
                console.error('跨域圖片無法讀取像素,需服務器配置 CORS', e);
            }
        };
        img.src = src;
    }

    // 3. 創建粒子系統
    function createParticles() {
        particles = [];
        const { data, width, height } = imgData;
        const scaleX = canvas.width / width;
        const scaleY = canvas.height / height;
        
        // 採樣像素 (每 CONFIG.density 個像素取樣)
        for (let y = 0; y < height; y += CONFIG.density) {
            for (let x = 0; x < width; x += CONFIG.density) {
                const i = (y * width + x) * 4;
                const alpha = data[i + 3];
                
                if (alpha > 128) { // 非透明像素
                    particles.push({
                        // 原始位置 (歸一化 0-1)
                        origX: x / width,
                        origY: y / height,
                        // 當前位置
                        x: (x / width) * canvas.width,
                        y: (y / height) * canvas.height,
                        // 顏色
                        r: data[i], g: data[i+1], b: data[i+2], a: alpha/255,
                        // 物理屬性
                        vx: 0, vy: 0,
                        ax: 0, ay: 0
                    });
                }
            }
        }
    }

    // 4. 動畫幀循環
    function animate() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        const mode = CONFIG.speedModes[speedMode];
        
        particles.forEach(p => {
            // 彈簧回歸原始位置
            const dx = (p.origX * canvas.width) - p.x;
            const dy = (p.origY * canvas.height) - p.y;
            
            p.ax = dx * 0.001; // 回歸力
            p.ay = dy * 0.001 + mode.gravity; // 重力
            
            p.vx = (p.vx + p.ax) * mode.friction;
            p.vy = (p.vy + p.ay) * mode.friction;
            
            p.x += p.vx;
            p.y += p.vy;
            
            // 繪製粒子
            ctx.beginPath();
            ctx.arc(p.x, p.y, CONFIG.particleRadius, 0, Math.PI * 2);
            ctx.fillStyle = `rgba(${p.r},${p.g},${p.b},${p.a})`;
            ctx.fill();
        });
        
        animationId = requestAnimationFrame(animate);
    }

    // 5. 公開 API
    return {
        create: function(containerId, imgSrc, mode) {
            speedMode = mode || 'normal';
            initCanvas(containerId);
            loadImage(imgSrc, function() {
                createParticles();
                animate();
            });
        },
        destroy: function() {
            cancelAnimationFrame(animationId);
            particles = [];
            if (canvas) canvas.remove();
        },
        setSpeed: function(mode) {
            if (CONFIG.speedModes[mode]) speedMode = mode;
        }
    };
})();

四、關鍵技術難點與優化

難點解決方案
跨域圖片污染 Canvas設置 img.crossOrigin = 'anonymous',服務器需返回 Access-Control-Allow-Origin: *
大圖片性能 (粒子過多)1. 增大 density 採樣間隔 2. 使用 Web Worker 計算物理 3. 渲染用 OffscreenCanvas (支持瀏覽器)
動畫流暢度使用 requestAnimationFrame、避免幀內創建對象、簡化繪製路徑
記憶體洩漏銷毀時清空粒子數組、取消動畫幀、移除 Canvas

五、擴展玩法

  • 鼠標交互:滑過產生排斥/吸引力場
  • 文字粒子化:Canvas 繪製文字後 getImageData
  • 3D 效果:引入 Three.js,粒子映射為 3D 球體
  • 視頻粒子化:用 requestVideoFrameCallback 處理視頻幀

六、總結

圖片粒子動畫展示了 Canvas 像素級操作的魅力。核心技術棧:Image → Canvas.drawImage → getImageData → 粒子系統物理模擬 → requestAnimationFrame 渲染。封裝為可配置庫 (ParticleImage) 後,一行代碼即可賦予任何圖片「生命」。

copyright © 萬盛學電腦網 all rights reserved