418 字
2 分钟
Canvas 粒子动画效果

效果说明#

本 Demo 实现了一个交谈粒子动画效果:

  • 🎨 随机颜色粒子在画布上运动
  • 🔗 距离较近的粒子之间自动连线
  • 🖱️ 鼠标移动时粒子会被吸引
  • 📱 自适应屏幕尺寸

核心代码#

HTML 结构#

<!DOCTYPE html>
<html>
<head>
<style>
body { margin: 0; overflow: hidden; }
canvas { display: block; background: #0a0a2e; }
</style>
</head>
<body>
<canvas id="particles"></canvas>
<script src="particles.js"></script>
</body>
</html>

JavaScript 实现#

const canvas = document.getElementById('particles');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
class Particle {
constructor() {
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
this.vx = (Math.random() - 0.5) * 2;
this.vy = (Math.random() - 0.5) * 2;
this.radius = Math.random() * 3 + 1;
}
update() {
this.x += this.vx;
this.y += this.vy;
// 边界反弹
if (this.x < 0 || this.x > canvas.width) this.vx *= -1;
if (this.y < 0 || this.y > canvas.height) this.vy *= -1;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
ctx.fill();
}
}
// 创建粒子
const particles = Array.from({ length: 100 }, () => new Particle());
function connectParticles() {
for (let i = 0; i < particles.length; i++) {
for (let j = i + 1; j < particles.length; j++) {
const dx = particles[i].x - particles[j].x;
const dy = particles[i].y - particles[j].y;
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist < 150) {
ctx.beginPath();
ctx.strokeStyle = `rgba(255,255,255,${1 - dist / 150})`;
ctx.lineWidth = 0.5;
ctx.moveTo(particles[i].x, particles[i].y);
ctx.lineTo(particles[j].x, particles[j].y);
ctx.stroke();
}
}
}
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
particles.forEach(p => {
p.update();
p.draw();
});
connectParticles();
requestAnimationFrame(animate);
}
animate();

技术要点#

  1. Canvas 2D 绑定 —— 使用 getContext('2d') 获取绑定上下文
  2. 粒子系统 —— 面向对象管理每个粒子的位置和速度
  3. 连线算法 —— 双重循环计算距离,距离阈值内绘制连线
  4. 动画循环 —— requestAnimationFrame 实现 60fps 动画
NOTE

粒子数量和连线距离可以根据设备性能调整,移动端建议减少粒子数量。

Canvas 粒子动画效果
https://blog.singlelyra.top/posts/demo-canvas-particles/
作者
ByteCraft
发布于
2026-03-16
许可协议
CC BY-NC-SA 4.0