用html做一个烟花动画
时间: 2023-12-22 09:04:10 浏览: 24
以下是一个基本的HTML烟花动画示例:
```html
<!DOCTYPE html>
<html>
<head>
<title>烟花动画</title>
<style>
canvas {
position: absolute;
top: 0;
left: 0;
z-index: -1;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
let particles = [];
function Particle() {
this.x = canvas.width / 2;
this.y = canvas.height / 2;
this.vx = Math.random() * 10 - 5;
this.vy = Math.random() * 10 - 5;
this.color = `hsl(${Math.random() * 360}, 100%, 50%)`;
}
Particle.prototype.update = function () {
this.x += this.vx;
this.y += this.vy;
this.vy += 0.1;
if (this.y > canvas.height) {
particles.splice(particles.indexOf(this), 1);
}
};
Particle.prototype.draw = function () {
ctx.beginPath();
ctx.arc(this.x, this.y, 5, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
};
document.addEventListener("click", function (event) {
for (let i = 0; i < 50; i++) {
const p = new Particle();
particles.push(p);
}
});
function loop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < particles.length; i++) {
const p = particles[i];
p.update();
p.draw();
}
requestAnimationFrame(loop);
}
loop();
</script>
</body>
</html>
```
这个示例创建了一个canvas元素,并在点击页面时发射50个粒子。每个粒子随机初始化其速度和颜色,并在每个帧更新其位置和速度。当粒子的y坐标大于canvas高度时,它将从数组中删除。整个动画由requestAnimationFrame循环驱动。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)