原生 JavaScript 烟花特效是一种利用 JavaScript 和 Canvas 绘制出的模拟烟花绽放效果的动画。
基础概念:
优势:
类型:
应用场景:
可能出现的问题及原因:
解决方法:
以下是一个简单的原生 JavaScript 烟花特效示例代码:
<canvas id="fireworkCanvas" width="800" height="600"></canvas>
<script>
const canvas = document.getElementById('fireworkCanvas');
const ctx = canvas.getContext('2d');
class Particle {
constructor(x, y, color) {
this.x = x;
this.y = y;
this.color = color;
this.vx = Math.random() * 4 - 2;
this.vy = Math.random() * -4 - 1;
this.gravity = 0.05;
this.alpha = 1;
}
update() {
this.x += this.vx;
this.y += this.vy;
this.vy += this.gravity;
this.alpha -= 0.01;
}
draw() {
ctx.save();
ctx.globalAlpha = this.alpha;
ctx.beginPath();
ctx.arc(this.x, this.y, 2, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
ctx.restore();
}
}
function createFirework() {
const x = canvas.width / 2;
const y = canvas.height;
const color = `hsl(${Math.random() * 360}, 100%, 50%)`;
const particles = [];
for (let i = 0; i < 100; i++) {
particles.push(new Particle(x, y, color));
}
return particles;
}
let fireworks = [];
function animate() {
requestAnimationFrame(animate);
ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
fireworks.forEach((firework, index) => {
firework.forEach(particle => {
particle.update();
particle.draw();
});
if (firework.every(p => p.alpha <= 0)) {
fireworks.splice(index, 1);
}
});
if (Math.random() < 0.05) {
fireworks.push(createFirework());
}
}
animate();
</script>
领取专属 10元无门槛券
手把手带您无忧上云