最近烟花代码比较火,大家在网上找的一些烟花不太好看,所以我用chatgpt经过不断改良使用量子写了一个满意的html代码!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Copyright by Zhangshao -->
<title>烟花</title>
<style>
body {
margin: 0;
overflow: hidden;
background-color: #000;
}
canvas {
display: block;
}
</style>
</head>
<body>
<canvas id="fireworksCanvas"></canvas>
<script>
document.addEventListener('DOMContentLoaded', function () {
const canvas = document.getElementById('fireworksCanvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
function Particle(x, y, color) {
this.x = x;
this.y = y;
this.color = color;
this.radius = Math.random() * 2 + 1; // 更细的粒子
this.velocity = {
x: (Math.random() - 0.5) * 20, // 更快的速度
y: (Math.random() - 0.5) * 20 // 更快的速度
};
this.opacity = 1;
}
Particle.prototype.draw = function () {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.globalAlpha = this.opacity;
ctx.fill();
ctx.globalAlpha = 1;
};
const particles = [];
function createParticles(x, y, color) {
for (let i = 0; i < 200; i++) { // 更多的粒子
const particle = new Particle(x, y, color);
particles.push(particle);
}
}
function autoCreateFireworks() {
const numberOfFireworks = 10; // 同时绽放的烟花数量
for (let i = 0; i < numberOfFireworks; i++) {
const x = Math.random() * canvas.width;
const y = Math.random() * (canvas.height / 2); // 降低初始高度
const color = `hsl(${Math.random() * 360}, 100%, 50%)`;
createParticles(x, y, color);
}
}
// 自动创建烟花,每隔0.5秒触发一次
setInterval(autoCreateFireworks, 500);
function animateParticles() {
for (let i = particles.length - 1; i >= 0; i--) {
particles[i].x += particles[i].velocity.x;
particles[i].y += particles[i].velocity.y;
particles[i].velocity.y += 0.1;
particles[i].opacity -= 0.03; // 调整透明度的减小速度
if (
particles[i].x < 0 ||
particles[i].x > canvas.width ||
particles[i].y < 0 ||
particles[i].y > canvas.height
) {
// 移出画布的粒子将被删除
particles.splice(i, 1);
} else {
particles[i].draw();
}
}
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
animateParticles();
requestAnimationFrame(animate);
}
animate();
// Resize canvas when the window is resized
window.addEventListener('resize', function () {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
});
</script>
</body>
</html>
解决了很多问题,但是由于达到效果,所以往后运行可能比较吃力,运行一会儿就可以了!
浏览效果请至:演示
抖音:CALL.ME.ZZ感谢观看!我们下次见!