hbuilderx放烟花代码html -
时间: 2025-06-13 16:59:31 浏览: 11
### HBuilderX中实现烟花效果的HTML代码
以下是在HBuilderX中实现烟花效果的完整HTML代码。该代码结合了HTML、CSS和JavaScript,确保在HBuilderX中可以直接运行并展示烟花效果。
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>烟花效果</title>
<style>
body {
margin: 0;
overflow: hidden;
background: black;
}
canvas {
display: block;
}
</style>
</head>
<body>
<canvas id="fireworksCanvas"></canvas>
<script>
const canvas = document.getElementById('fireworksCanvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
window.addEventListener('resize', () => {
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() * 5 + 1;
this.velocity = {
x: (Math.random() - 0.5) * 10,
y: (Math.random() - 0.5) * 10
};
this.alpha = 1;
}
draw() {
ctx.save();
ctx.globalAlpha = this.alpha;
ctx.beginPath();
ctx.fillStyle = this.color;
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
}
update() {
this.draw();
this.x += this.velocity.x;
this.y += this.velocity.y;
this.alpha -= 0.01;
if (this.alpha <= 0) {
this.alpha = 0;
}
}
}
class Firework {
constructor(x, y, color) {
this.particles = [];
for (let i = 0; i < 100; i++) {
this.particles.push(new Particle(x, y, color));
}
}
draw() {
this.particles.forEach(particle => particle.draw());
}
update() {
this.particles = this.particles.filter(particle => particle.alpha > 0);
this.particles.forEach(particle => particle.update());
}
}
const fireworks = [];
const colors = ['#FF0000', '#FFFF00', '#00FF00', '#0000FF', '#FF00FF'];
function initFirework() {
const x = Math.random() * canvas.width;
const y = canvas.height + Math.random() * 100;
const color = colors[Math.floor(Math.random() * colors.length)];
fireworks.push(new Firework(x, y, color));
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
fireworks.forEach((firework, index) => {
firework.update();
firework.draw();
if (firework.particles.length === 0) {
fireworks.splice(index, 1);
}
});
requestAnimationFrame(animate);
}
setInterval(initFirework, 100);
animate();
</script>
</body>
</html>
```
### 说明
上述代码实现了烟花效果[^3],主要包含以下几个部分:
1. **HTML结构**:通过`<canvas>`标签绘制动画。
2. **CSS样式**:设置页面背景为黑色,隐藏滚动条以获得更好的视觉效果。
3. **JavaScript逻辑**:
- 定义了`Particle`类,用于创建单个粒子,并控制其大小、颜色、速度和透明度。
- 定义了`Firework`类,用于生成一组粒子,模拟烟花爆炸的效果。
- 使用`requestAnimationFrame`方法实现动画循环,不断更新和绘制粒子。
此代码无需任何外部图片资源,完全依赖JavaScript生成动态效果[^3]。
阅读全文
相关推荐

















