Canvas 粒子背景特效(可调数量/颜色/连线距离)
Canvas 粒子背景:粒子飘动 + 近距离连线效果,数量/颜色/连线距离/速度实时可调,落地页/登录页背景首选,复制即用。
效果演示(真实可交互)
完整代码
<canvas id="particles" style="width:100%;height:320px;background:#0f1117;"></canvas>
const canvas = document.getElementById('particles');
const ctx = canvas.getContext('2d');
let W, H, particles = [];
const cfg = { count: 70, dist: 120, color: '#6c8cff' };
function resize() {
const r = canvas.getBoundingClientRect();
const dpr = window.devicePixelRatio || 1;
W = canvas.width = r.width * dpr;
H = canvas.height = r.height * dpr;
ctx.scale(dpr, dpr);
}
function init() {
particles = [];
for (let i = 0; i < cfg.count; i++) {
particles.push({
x: Math.random() * W, y: Math.random() * H,
vx: (Math.random() - .5) * .6, vy: (Math.random() - .5) * .6,
r: Math.random() * 2 + 1,
});
}
}
function step() {
ctx.clearRect(0, 0, W, H);
for (const p of particles) {
p.x += p.vx; p.y += p.vy;
if (p.x < 0 || p.x > W) p.vx *= -1;
if (p.y < 0 || p.y > H) p.vy *= -1;
ctx.beginPath();
ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2);
ctx.fillStyle = cfg.color; ctx.fill();
}
for (let i = 0; i < particles.length; i++) {
for (let j = i + 1; j < particles.length; j++) {
const a = particles[i], b = particles[j];
const d = Math.hypot(a.x - b.x, a.y - b.y);
if (d < cfg.dist) {
ctx.beginPath();
ctx.moveTo(a.x, a.y); ctx.lineTo(b.x, b.y);
ctx.strokeStyle = cfg.color;
ctx.globalAlpha = 1 - d / cfg.dist;
ctx.stroke();
}
}
}
ctx.globalAlpha = 1;
requestAnimationFrame(step);
}
resize(); init(); step();
window.addEventListener('resize', () => { resize(); init(); });
参数调节
| 参数 | 位置 | 说明 |
|---|---|---|
| 粒子数量 | cfg.count | 20-150,越多越密,性能开销越大 |
| 连线距离 | cfg.dist | 粒子间距小于此值才连线(像素) |
| 颜色 | cfg.color | 粒子与连线颜色 |
| 速度 | vx/vy: .6 | 越大飘得越快 |
| 粒子大小 | Math.random()*2+1 | 半径范围 |
性能说明
- 连线是 O(n²) 计算,150 粒子 ≈ 1.1 万次距离判断,现代设备无压力
- 超过 200 粒子建议开启
requestAnimationFrame节流或降低连线计算(每隔一帧连线) - 已适配
devicePixelRatio,高分屏不模糊 - 移动端建议粒子数 ≤ 60,避免耗电
常见问题
Q: 和 particles.js 什么关系? 无依赖关系。本组件为粤喵自研实现(约 60 行),比 particles.js(100+KB)轻量得多,效果相同。
Q: 怎么让它只在首页显示? 把 canvas 放进首页的容器里即可;想隐藏就 display:none 并停止动画。
Q: 能做点击产生新粒子吗? 可以,在 canvas 的 click 事件里 particles.push({x,y,...}) 即可,参考上方代码结构。
Q: 可以商用吗? 可以,本组件为粤喵自研原创,免费商用无需署名。
常见问题
这个组件可以商用吗?
可以。本组件为粤喵自研原创,可免费用于个人和商业项目,无需署名。
浏览器兼容性如何?
支持所有现代浏览器(Chrome / Firefox / Safari / Edge 最新版本)。旧版 IE 不支持 CSS 动画相关特性。
怎么修改动画参数?
直接调整 CSS 中的 animation-duration(时长)、animation-timing-function(缓动曲线)等属性即可,代码中有注释说明。