將靜態圖片轉化為動態粒子動畫是創意前端的經典案例。核心原理:使用 Canvas getImageData() 獲取像素數據,提取非透明像素點,將每個像素作為粒子進行物理模擬動畫。本文解析完整實現邏輯並提供封裝庫設計思路。
getImageData() 獲取 RGBA 數據
<!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>
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 |
requestVideoFrameCallback 處理視頻幀圖片粒子動畫展示了 Canvas 像素級操作的魅力。核心技術棧:Image → Canvas.drawImage → getImageData → 粒子系統物理模擬 → requestAnimationFrame 渲染。封裝為可配置庫 (ParticleImage) 後,一行代碼即可賦予任何圖片「生命」。