用javascript实现烟花代码
时间: 2024-06-13 20:09:58 浏览: 14
以下是一个简单的用JavaScript实现烟花效果的代码示例:
```html
<!DOCTYPE html>
<html>
<head>
<style>
canvas {
display: block;
margin: 0 auto;
background-color: black;
}
</style>
</head>
<body>
<canvas id="fireworks"></canvas>
<script>
const canvas = document.getElementById('fireworks');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
class Firework {
constructor(x, y) {
this.x = x;
this.y = y;
this.size = Math.random() * 5 + 1;
this.speedX = Math.random() * 6 - 3;
this.speedY = Math.random() * 3 + 2;
this.color = `hsl(${Math.random() * 360}, 100%, 50%)`;
}
update() {
this.x += this.speedX;
this.y += this.speedY;
this.size -= 0.1;
}
draw() {
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fill();
}
}
let fireworks = [];
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
fireworks.forEach((firework, index) => {
firework.update();
firework.draw();
if (firework.size <= 0.3) {
fireworks.splice(index, 1);
}
});
requestAnimationFrame(animate);
}
for (let i = 0; i < 100; i++) {
fireworks.push(new Firework(Math.random() * canvas.width, Math.random() * canvas.height));
}
animate();
</script>
</body>
</html>
```
这段代码创建了一个HTML页面,其中包含一个全屏的canvas元素。JavaScript代码定义了一个Firework类,用于表示烟花。每个烟花都有一个随机的位置、大小、速度和颜色。animate函数负责更新和绘制烟花,当烟花的大小减小到0.3以下时,将其从数组中移除。最后,我们创建了100个烟花并开始动画循环。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![](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)