用html css js 制作烟花
时间: 2023-10-03 09:06:57 浏览: 101
用html写的烟花,过年过节、哄女朋友都可以用
5星 · 资源好评率100%
好的,制作烟花可以使用 HTML、CSS 和 JavaScript 来实现。下面是一个简单的示例代码:
首先,在 HTML 文件中创建一个画布元素:
```html
<canvas id="canvas"></canvas>
```
然后,在 CSS 文件中设置画布的样式:
```css
#canvas {
background-color: black;
width: 100%;
height: 100%;
}
```
接着,在 JavaScript 文件中编写绘制烟花的代码:
```javascript
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
class Particle {
constructor(x, y, color) {
this.x = x;
this.y = y;
this.color = color;
this.vx = Math.random() * 10 - 5;
this.vy = Math.random() * 10 - 5;
this.alpha = 1;
}
update() {
this.x += this.vx;
this.y += this.vy;
this.alpha -= 0.01;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, 5, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.globalAlpha = this.alpha;
ctx.fill();
ctx.closePath();
}
isDead() {
return this.alpha <= 0;
}
}
class Firework {
constructor(x, y) {
this.x = x;
this.y = y;
this.particles = [];
this.color = `hsl(${Math.random() * 360}, 100%, 50%)`;
}
update() {
if (Math.random() < 0.2) {
this.explode();
}
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, 3, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
ctx.closePath();
}
explode() {
for (let i = 0; i < 50; i++) {
const particle = new Particle(this.x, this.y, this.color);
this.particles.push(particle);
}
}
isDead() {
return this.particles.length === 0;
}
drawParticles() {
this.particles.forEach((particle) => {
particle.update();
particle.draw();
});
this.particles = this.particles.filter((particle) => !particle.isDead());
}
}
const fireworks = [];
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
fireworks.forEach((firework) => {
firework.update();
firework.drawParticles();
firework.draw();
});
fireworks = fireworks.filter((firework) => !firework.isDead());
}
function createFirework() {
const firework = new Firework(Math.random() * canvas.width, canvas.height);
fireworks.push(firework);
}
setInterval(createFirework, 1000);
setInterval(draw, 30);
```
这段代码创建了两个类:Particle 和 Firework。Particle 表示烟花中的每个粒子,Firework 表示烟花本身。createFirework 函数定时创建烟花,draw 函数负责绘制烟花和烟花中的粒子。
最后,在 JavaScript 文件中调用 draw 函数和 createFirework 函数即可实现烟花的效果。
希望这个示例代码能够帮到你。
阅读全文