用html写一个烟花绽放的动态页面
时间: 2023-09-29 20:07:32 浏览: 48
这是一个使用HTML、CSS和JavaScript编写的烟花绽放动态页面的示例:
```html
<!DOCTYPE html>
<html>
<head>
<style>
/*设置背景颜色*/
body {
background-color: black;
}
/*设置烟花样式*/
.firework {
position: absolute;
width: 5px;
height: 5px;
border-radius: 50%;
background-color: white;
}
</style>
</head>
<body>
<script>
// 定义烟花数组
var fireworks = [];
// 获取画布
var canvas = document.getElementById("canvas");
// 设置画布宽度和高度
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// 获取画笔
var ctx = canvas.getContext("2d");
// 定义烟花类
function Firework() {
// 随机位置
this.x = Math.random() * canvas.width;
this.y = canvas.height;
// 随机颜色
this.color = "hsl(" + Math.random() * 360 + ", 100%, 50%)";
// 随机速度
this.speed = Math.random() * 5 + 5;
// 绘制烟花
this.draw = function() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, 5, 5);
};
// 更新烟花位置
this.update = function() {
this.y -= this.speed;
};
}
// 添加烟花
function addFirework() {
fireworks.push(new Firework());
}
// 定时器每秒添加一个烟花
setInterval(addFirework, 1000);
// 动画循环
function animate() {
requestAnimationFrame(animate);
// 清除画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制所有烟花
for (var i = 0; i < fireworks.length; i++) {
fireworks[i].draw();
fireworks[i].update();
}
}
animate();
</script>
<canvas id="canvas"></canvas>
</body>