### JS烟花特效教程:打造绚丽网页视觉效果
在网页设计中,添加动态和视觉效果是吸引用户注意力、提升用户体验的重要手段之一,烟花特效作为一种既浪漫又富有节日氛围的元素,经常被用于庆祝活动、节日页面或是游戏界面中,本教程将引导你通过JavaScript(JS)和HTML5 Canvas API来创建一个简单的烟花特效,为你的网页增添一抹亮丽的色彩。
#### 第一步:准备HTML结构
我们需要在HTML文件中设置一个``元素,作为绘制烟花的画布。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>JS烟花特效</title> <style> body, html { height: 100%; margin: 0; overflow: hidden; } canvas { display: block; background: #000; } </style> </head> <body> <canvas id="fireworksCanvas"></canvas> <script src="fireworks.js"></script> </body> </html>
#### 第二步:编写JavaScript逻辑
接下来,在`fireworks.js`文件中,我们将编写JavaScript代码来创建和管理烟花。
##### 1. 初始化Canvas
我们需要获取Canvas元素并设置其大小。
const canvas = document.getElementById('fireworksCanvas'); const ctx = canvas.getContext('2d'); // 设置Canvas大小 canvas.width = window.innerWidth; canvas.height = window.innerHeight; // 监听窗口大小变化 window.addEventListener('resize', () => { canvas.width = window.innerWidth; canvas.height = window.innerHeight; });
##### 2. 定义烟花粒子
每个烟花由多个粒子组成,我们需要定义一个粒子类。
class Particle { constructor(x, y, color, size, velocity) { this.x = x; this.y = y; this.color = color; this.size = size; this.velocity = velocity; this.alpha = 1; } update() { this.y -= this.velocity.y; this.x += this.velocity.x * Math.cos(this.angle); this.y += this.velocity.x * Math.sin(this.angle); this.alpha -= 0.01; } draw() { ctx.globalAlpha = this.alpha; ctx.fillStyle = this.color; ctx.beginPath(); ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2); ctx.fill(); } }
##### 3. 创建烟花爆炸效果
我们需要一个函数来模拟烟花的爆炸,即生成多个粒子。
function explode(x, y) { const colors = ['#FF0000', '#FFFF00', '#00FF00', '#0000FF', '#FF00FF']; const numParticles = 100; const velocity = { x: 3, y: -3 }; for (let i = 0; i < numParticles; i++) { const angle = Math.random() * 2 * Math.PI; const size = Math.random() * 5 + 1; const color = colors[Math.floor(Math.random() * colors.length)]; particles.push(new Particle(x, y, color, size, { x: velocity.x * Math.cos(angle), y: velocity.y + velocity.x * Math.sin(angle) }, angle)); } }
##### 4. 动画循环
我们需要一个动画循环来更新和绘制所有粒子。
```javascript
let particles = [];
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
particles = particles.filter(particle => {
particle.update();
particle.draw();
return particle.alpha > 0;
});
requestAnimationFrame(animate);
}
// 触发烟花
explode(canvas.width / 2, canvas.height);
animate();