在JavaScript中实现点击产生烟花效果,通常会结合HTML5的Canvas绘图技术和一些数学算法来模拟烟花的运动轨迹和绽放效果。以下是基础概念、优势、类型、应用场景以及实现方法的概述:
requestAnimationFrame
方法实现平滑的动画效果。以下是一个简单的点击产生烟花效果的示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>点击烟花效果</title>
<style>
canvas {
display: block;
background-color: black;
}
</style>
</head>
<body>
<canvas id="fireworkCanvas"></canvas>
<script>
const canvas = document.getElementById('fireworkCanvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
class Particle {
constructor(x, y, color) {
this.x = x;
this.y = y;
this.color = color;
this.size = Math.random() * 3 + 1;
this.speedX = Math.random() * 6 - 3;
this.speedY = Math.random() * -9 - 2;
this.gravity = 0.05;
this.alpha = 1;
this.decay = Math.random() * 0.015 + 0.005;
}
update() {
this.x += this.speedX;
this.y += this.speedY;
this.speedY += this.gravity;
this.alpha -= this.decay;
}
draw(ctx) {
ctx.save();
ctx.globalAlpha = this.alpha;
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
ctx.restore();
}
}
function createFirework(x, y) {
const particles = [];
const particleCount = 100;
const hue = Math.random() * 360;
for (let i = 0; i < particleCount; i++) {
particles.push(new Particle(x, y, `hsl(${hue}, 100%, 50%)`));
}
return particles;
}
let fireworks = [];
canvas.addEventListener('click', (e) => {
const rect = canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
fireworks.push(createFirework(x, y));
});
function animate() {
requestAnimationFrame(animate);
ctx.fillStyle = 'rgba(0, 0, 0, 0.2)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
fireworks.forEach((firework, index) => {
firework.forEach(particle => {
particle.update();
particle.draw(ctx);
});
firework = firework.filter(particle => particle.alpha > 0);
if (firework.length === 0) {
fireworks.splice(index, 1);
}
});
}
animate();
</script>
</body>
</html>
requestAnimationFrame
的polyfill来兼容旧版浏览器。这个示例代码提供了一个基本的点击烟花效果实现,你可以根据需要调整参数和添加更多特性来定制效果。
领取专属 10元无门槛券
手把手带您无忧上云