2025跨年烟花代码可复制
时间: 2024-12-27 14:15:28 浏览: 48
### 实现2025新年烟花效果的代码示例
为了创建一个具有吸引力的新年烟花效果,通常会采用HTML5 Canvas API来绘制动画。下面是一个简单的JavaScript例子,该脚本能够模拟烟花绽放的效果:
```javascript
const canvas = document.getElementById('fireworksCanvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
class Particle {
constructor(x, y) {
this.x = x;
this.y = y;
this.color = `hsl(${Math.random() * 360}, 100%, 50%)`;
this.size = Math.random() * 4 + 1;
this.speedX = Math.random() * 6 - 3;
this.speedY = Math.random() * -15;
this.gravity = 0.1;
this.friction = 0.97;
}
update() {
this.speedY += this.gravity;
this.speedX *= this.friction;
this.speedY *= this.friction;
this.x += this.speedX;
this.y += this.speedY;
this.size *= 0.98;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
}
}
function animateParticles(particles) {
particles.forEach((particle, index) => {
particle.update();
particle.draw();
if (particle.size <= 0.2 || particle.y >= canvas.height) {
particles.splice(index, 1);
}
});
}
function createExplosion(x, y) {
const particlesCount = 100;
let particles = [];
for (let i = 0; i < particlesCount; i++) {
particles.push(new Particle(x, y));
}
function explosionLoop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (particles.length > 0) {
requestAnimationFrame(explosionLoop);
animateParticles(particles);
}
}
explosionLoop();
}
// Trigger explosions at random intervals or on user interaction.
setInterval(() => {
const startX = Math.random() * canvas.width;
const startY = canvas.height;
createExplosion(startX, startY);
}, 2000); // Adjust interval as needed.
window.addEventListener('click', event => {
const mouseX = event.clientX;
const mouseY = event.clientY;
createExplosion(mouseX, mouseY);
});
```
此段代码定义了一个`Particle`类用来表示单个粒子,并实现了爆炸逻辑以及触发机制[^1]。
阅读全文