flappy2048烟花特效具体代码
时间: 2023-09-28 14:07:29 浏览: 36
以下是一个简单的实现 Flappy2048 烟花特效的示例代码:
```
// 获取画布元素
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// 定义烟花粒子类
class Particle {
constructor(x, y, vx, vy, color) {
this.x = x;
this.y = y;
this.vx = vx;
this.vy = vy;
this.color = color;
this.alpha = 1;
}
// 更新烟花粒子状态
update() {
this.x += this.vx;
this.y += this.vy;
this.alpha -= 0.01;
}
// 绘制烟花粒子
draw() {
ctx.save();
ctx.globalAlpha = this.alpha;
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, 2, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
}
// 判断烟花粒子是否消失
isDead() {
return this.alpha <= 0;
}
}
// 定义烟花类
class Firework {
constructor(x, y) {
this.x = x;
this.y = y;
this.particles = [];
this.createParticles();
}
// 创建烟花粒子
createParticles() {
for (let i = 0; i < 20; i++) {
const angle = Math.random() * Math.PI * 2;
const speed = Math.random() * 5 + 2;
const vx = Math.cos(angle) * speed;
const vy = Math.sin(angle) * speed;
const color = `rgb(${Math.floor(Math.random() * 256)}, ${Math.floor(Math.random() * 256)}, ${Math.floor(Math.random() * 256)})`;
const particle = new Particle(this.x, this.y, vx, vy, color);
this.particles.push(particle);
}
}
// 更新烟花状态
update() {
this.particles.forEach(particle => particle.update());
this.particles = this.particles.filter(particle => !particle.isDead());
}
// 绘制烟花
draw() {
this.particles.forEach(particle => particle.draw());
}
// 判断烟花是否消失
isDead() {
return this.particles.length === 0;
}
}
// 定义烟花效果类
class FireworkEffect {
constructor() {
this.fireworks = [];
}
// 添加烟花
addFirework(x, y) {
const firework = new Firework(x, y);
this.fireworks.push(firework);
}
// 更新烟花效果状态
update() {
this.fireworks.forEach(firework => firework.update());
this.fireworks = this.fireworks.filter(firework => !firework.isDead());
}
// 绘制烟花效果
draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
this.fireworks.forEach(firework => firework.draw());
}
}
// 创建烟花效果实例
const fireworkEffect = new FireworkEffect();
// 监听鼠标点击事件
canvas.addEventListener('click', event => {
const x = event.clientX - canvas.offsetLeft;
const y = event.clientY - canvas.offsetTop;
fireworkEffect.addFirework(x, y);
});
// 定时更新和绘制烟花效果
setInterval(() => {
fireworkEffect.update();
fireworkEffect.draw();
}, 20);
```
在以上代码中,烟花效果主要由三个类组成:
- `Particle` 类:用于表示单个烟花粒子,包括位置、速度、颜色和透明度等属性,以及更新、绘制和判断是否消失等方法。
- `Firework` 类:用于表示单个烟花,包括位置和一组烟花粒子等属性,以及创建、更新、绘制和判断是否消失等方法。
- `FireworkEffect` 类:用于表示整个烟花效果,包括一组烟花等属性,以及添加、更新和绘制等方法。
通过监听鼠标点击事件,可以在用户点击画布时添加烟花,并定时更新和绘制整个烟花效果。