创建一个烟花动画效果在前端开发中是一个相对复杂的任务,因为它涉及到许多数学和物理概念,如重力、速度和加速度。以下是一个简单的烟花动画效果的示例代码,使用HTML5的<canvas>
元素和JavaScript。
- HTML:
<!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, canvas {
margin: 0;
padding: 0;
overflow: hidden;
width: 100%;
height: 100%;
position: absolute;
}
</style>
</head>
<body>
<canvas id="fireworksCanvas"></canvas>
<script src="fireworks.js"></script>
</body>
</html>
- JavaScript (
fireworks.js
):
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.size = Math.random() * 5 + 1;
this.speedX = Math.random() * 6 - 3;
this.speedY = Math.random() * 6 - 3;
this.gravity = 0.1;
this.alpha = Math.random();
}
update() {
this.speedY += this.gravity;
this.x += this.speedX;
this.y += this.speedY;
this.alpha -= 0.005;
}
draw() {
ctx.globalAlpha = this.alpha;
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.closePath();
ctx.fillStyle = 'rgba(255, 100, 0, ' + this.alpha + ')';
ctx.fill();
}
}
let particles = [];
function animate() {
requestAnimationFrame(animate);
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (Math.random() < 0.02) {
particles.push(new Particle(canvas.width / 2, canvas.height));
}
for (let i = particles.length - 1; i >= 0; i--) {
particles[i].update();
particles[i].draw();
if (particles[i].alpha < 0) {
particles.splice(i, 1);
}
}
}
animate();
这个示例创建了一个简单的烟花效果,其中粒子从屏幕底部中心随机发射,并受到重力的影响。你可以根据需要调整粒子的数量、速度、大小和颜色等属性来定制效果。