
想让网页看起来更生动?粒子特效是个不错的选择。用html5结合javaScript,你可以轻松实现炫酷的动画效果。核心是利用canvas绘制粒子,并通过动画循环实时更新位置。
1. 创建canvas画布
首先在HTML中插入<canvas>标签,设置宽高:
<canvas id="particleCanvas" width="800" height="600"></canvas>
#particleCanvas { display: block; background: #000; }
2. 初始化javascript环境
获取canvas上下文,准备绘图:
立即学习“前端免费学习笔记(深入)”;
const canvas = document.getElementById('particleCanvas'); const ctx = canvas.getContext('2d');
定义粒子数量和存储数组:
const particleCount = 100; const particles = [];
3. 构建粒子对象
每个粒子包含位置、速度、大小、颜色等属性:
function Particle() { 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.size = Math.random() * 5 + 1; this.color = 'hsl(' + Math.random() * 360 + ', 80%, 60%)'; } <p>Particle.prototype.draw = function() { ctx.beginPath(); ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2); ctx.fillStyle = this.color; ctx.fill(); };</p><p>Particle.prototype.update = function() { if (this.x < 0 || this.x > canvas.width) this.vx <em>= -1; if (this.y < 0 || this.y > canvas.height) this.vy </em>= -1; this.x += this.vx; this.y += this.vy; };</p>
4. 启动动画循环
创建多个粒子并持续重绘:
for (let i = 0; i < particleCount; i++) { particles.push(new Particle()); } <p>function animate() { ctx.clearRect(0, 0, canvas.width, canvas.height); for (let i = 0; i < particles.length; i++) { particles[i].update(); particles[i].draw(); } requestAnimationFrame(animate); }</p><p>animate();</p>
5. 添加连线与交互(进阶)
让粒子之间产生连线,增强视觉效果。检测鼠标位置,使粒子向光标靠近:
let mouse = { x: undefined, y: undefined }; <p>window.addEventListener('mousemove', function(e) { mouse.x = e.x; mouse.y = e.y; });</p><p>// 在update中加入距离判断 Particle.prototype.update = function() { let dx = mouse.x - this.x; let dy = mouse.y - this.y; let distance = Math.sqrt(dx<em>dx + dy</em>dy);</p><p>if (distance < 100) { this.vx -= dx / 5000; this.vy -= dy / 5000; } // ...其他逻辑 };</p>
再添加连接线逻辑:
function connectParticles() { for (let a = 0; a < particles.length; a++) { for (let b = a + 1; b < particles.length; b++) { let dx = particles[a].x - particles[b].x; let dy = particles[a].y - particles[b].y; let distance = Math.sqrt(dx*dx + dy*dy); <pre class='brush:php;toolbar:false;'> if (distance < 80) { ctx.beginPath(); ctx.strokeStyle = particles[a].color; ctx.lineWidth = 0.5; ctx.moveTo(particles[a].x, particles[a].y); ctx.lineTo(particles[b].x, particles[b].y); ctx.stroke(); } }
} }
在animate函数中调用connectParticles()。
基本上就这些。掌握canvas绘图和requestAnimationFrame机制后,你可以自由扩展:比如添加重力、碰撞检测、响应式布局适配,甚至音频可视化。不复杂但容易忽略细节,比如清屏时机、性能优化(避免过多粒子)、内存释放等。


