<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>烟花特效</title>
<style>
body {
margin: 0;
overflow: hidden;
background: black;
}
canvas {
display: block;
}
</style>
</head>
<body>
<canvas id="fireworks"></canvas>
<script>
// 烟花特效的JavaScript代码
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.color = `hsl(${Math.random() * 360}, 100%, 50%)`;
this.particles = [];
this.createParticles();
}
createParticles() {
for (let i = 0; i < 100; i++) {
this.particles.push(new Particle(this.x, this.y, this.color));
}
}
update() {
this.particles.forEach(particle => particle.update());
}
draw() {
this.particles.forEach(particle => particle.draw());
}
}
class Particle {
constructor(x, y, color) {
this.x = x;
this.y = y;
this.color = color;
this.size = Math.random() * 4 + 1;
this.speedX = Math.random() * 6 - 3;
this.speedY = Math.random() * -15;
this.gravity = 0.1;
this.friction = 0.95;
}
update() {
this.speedY += this.gravity;
this.speedX *= this.friction;
this.speedY *= this.friction;
this.x += this.speedX;
this.y += this.speedY;
this.size *= 0.95;
}
draw() {
if (this.size > 0.2) {
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
}
}
}
let fireworks = [];
function animate() {
ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
fireworks.forEach((firework, index) => {
firework.update();
firework.draw();
if (firework.particles.every(particle => particle.size <= 0.2)) {
fireworks.splice(index, 1);
}
});
requestAnimationFrame(animate);
}
function init() {
setInterval(() => {
const x = Math.random() * canvas.width;
const y = canvas.height + 100;
fireworks.push(new Firework(x, y));
}, 1000);
}
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
init();
animate();
</script>
</body>
</html>
这段代码实现了一个简单的烟花特效,主要分为以下几个部分:
<canvas>
元素用于绘制烟花。Firework
和Particle
,分别表示烟花和烟花中的粒子。Firework
类负责创建和管理多个Particle
对象。Particle
类定义了每个粒子的位置、速度、颜色等属性,并实现了更新和绘制方法。animate
函数用于不断重绘画布并更新所有烟花的状态。init
函数每隔一秒在随机位置生成一个新的烟花。通过这些代码,你可以在网页上看到绚丽的烟花效果。
上一篇:html footer
下一篇:html 特殊符号
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站