<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>New Year Fireworks</title>
<style>
body {
margin: 0;
overflow: hidden;
background: #000;
}
canvas {
display: block;
}
</style>
</head>
<body>
<canvas id="fireworks"></canvas>
<script>
const canvas = document.getElementById('fireworks');
const ctx = canvas.getContext('2d');
let particles = [];
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
class Particle {
constructor(x, y, color, velocityX, velocityY, size) {
this.x = x;
this.y = y;
this.color = color;
this.velocityX = velocityX;
this.velocityY = velocityY;
this.size = size;
this.life = 100;
}
update() {
this.x += this.velocityX;
this.y += this.velocityY;
this.velocityY += 0.05;
this.life -= 0.5;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
ctx.closePath();
}
}
class Firework {
constructor(x, y, color) {
this.x = x;
this.y = y;
this.color = color;
this.particles = [];
this.explode();
}
explode() {
const numberOfParticles = 100;
for (let i = 0; i < numberOfParticles; i++) {
const angle = Math.random() * Math.PI * 2;
const velocity = Math.random() * 3 + 1;
const velocityX = Math.cos(angle) * velocity;
const velocityY = Math.sin(angle) * velocity;
const size = Math.random() * 3 + 1;
const particle = new Particle(this.x, this.y, this.color, velocityX, velocityY, size);
this.particles.push(particle);
}
}
update() {
for (let i = this.particles.length - 1; i >= 0; i--) {
const particle = this.particles[i];
particle.update();
if (particle.life <= 0) {
this.particles.splice(i, 1);
}
}
}
draw() {
for (const particle of this.particles) {
particle.draw();
}
}
}
function createFirework() {
const x = Math.random() * canvas.width;
const y = Math.random() * canvas.height;
const color = `hsl(${Math.random() * 360}, 100%, 50%)`;
const firework = new Firework(x, y, color);
return firework;
}
let fireworks = [];
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (Math.random() < 0.02) {
fireworks.push(createFirework());
}
for (const firework of fireworks) {
firework.update();
firework.draw();
}
requestAnimationFrame(animate);
}
animate();
</script>
</body>
</html>
编辑排版|白恩嘉 叶申贵
责任编辑|张婧争
指导老师|田蕊