用HTML5写一段烟花秀
时间: 2023-03-16 20:44:43 浏览: 50
我可以为您提供一个简单的HTML5烟花秀示例:
<!DOCTYPE html>
<html>
<head>
<title>烟花秀</title>
<style>
canvas {
background-color: #000;
}
</style>
</head>
<body>
<canvas id="canvas" width="500" height="500"></canvas>
<script>
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
let particles = [];
let colors = ["#FF1461", "#18FF92", "#5A87FF", "#FBF38C"];
// 初始化烟花
function init() {
particles = [];
for (let i = 0; i < 100; i++) {
let x = Math.random() * canvas.width;
let y = Math.random() * canvas.height;
let direction = {
x: -1 + Math.random() * 2,
y: -1 + Math.random() * 2
};
let color = colors[Math.floor(Math.random() * colors.length)];
let size = 1 + Math.random() * 3;
particles.push(new Particle(x, y, direction, color, size));
}
}
// 烟花类
class Particle {
constructor(x, y, direction, color, size) {
this.x = x;
this.y = y;
this.direction = direction;
this.color = color;
this.size = size;
}
// 绘制
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2, false);
ctx.fillStyle = this.color;
ctx.fill();
}
// 烟花的更新
update() {
this.x += this.direction.x;
this.y += this.direction.y;
// 烟花反弹
if (this.x >= canvas.width || this.x <= 0) {
this.direction.x *= -1;
}
if (this.y >= canvas.height || this.y <= 0) {
this.direction.y *= -1;
}
// 绘制
this.draw();
}
}
// 更新所有烟花
function animate() {
requestAnimationFrame(animate);
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < particles.length; i++) {
particles[i].update();
}
}
init();
animate();
</script>
</body>
</html>