以下是一个使用 JavaScript 和 Canvas 实现简单烟花特效的示例:
HTML 部分:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>烟花特效</title>
</head>
<body>
<canvas id="fireworkCanvas"></canvas>
<script src="firework.js"></script>
</body>
</html>
JavaScript 部分(firework.js):
const canvas = document.getElementById('fireworkCanvas');
const ctx = canvas.getContext('2d');
// 设置画布大小为窗口大小
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// 烟花粒子类
class Particle {
constructor(x, y, color) {
this.x = x;
this.y = y;
this.color = color;
this.size = Math.random() * 3 + 1;
this.speedX = Math.random() * 6 - 3;
this.speedY = Math.random() * -6 - 2;
this.gravity = 0.05;
this.alpha = 1;
this.decay = Math.random() * 0.015 + 0.005;
}
update() {
this.x += this.speedX;
this.y += this.speedY;
this.speedY += this.gravity;
this.alpha -= this.decay;
}
draw(ctx) {
ctx.save();
ctx.globalAlpha = this.alpha;
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
ctx.restore();
}
}
// 烟花类
class Firework {
constructor(x, y) {
this.x = x;
this.y = y;
this.particles = [];
this.color = `hsl(${Math.random() * 360}, 100%, 50%)`;
this.createParticles();
}
createParticles() {
const particleCount = 100;
for (let i = 0; i < particleCount; i++) {
this.particles.push(new Particle(this.x, this.y, this.color));
}
}
update() {
this.particles.forEach(particle => particle.update());
}
draw(ctx) {
this.particles.forEach(particle => particle.draw(ctx));
}
}
// 创建烟花数组
let fireworks = [];
// 动画循环
function animate() {
requestAnimationFrame(animate);
ctx.fillStyle = 'rgba(0, 0, 0, 0.2)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
fireworks.forEach((firework, index) => {
firework.update();
firework.draw(ctx);
if (firework.particles.every(particle => particle.alpha <= 0)) {
fireworks.splice(index, 1);
}
});
// 随机创建烟花
if (Math.random() < 0.05) {
fireworks.push(new Firework(canvas.width / 2, canvas.height));
}
}
animate();
基础概念:
优势:
应用场景:
可能出现的问题及解决方法:
领取专属 10元无门槛券
手把手带您无忧上云