要在前端实现一个烟花效果,可以借助 Canvas 技术来绘制动画。下面是一个简单的实现示例:
HTML 代码:
<canvas id="fireworks"></canvas>
CSS 代码:
/* 设置画布大小 */
#fireworks {
width: 100%;
height: 100%;
background-color: black;
}
JavaScript 代码:
// 获取画布和上下文
var canvas = document.getElementById('fireworks');
var ctx = canvas.getContext('2d');
// 设置画布大小和分辨率
var width, height, resolution;
function setCanvasSize() {
width = window.innerWidth;
height = window.innerHeight;
resolution = window.devicePixelRatio || 1;
canvas.width = width * resolution;
canvas.height = height * resolution;
}
setCanvasSize();
// 创建烟花类
class Firework {
constructor() {
this.x = Math.random() * width;
this.y = height;
this.color = randomColor();
this.vx = Math.random() * 4 - 2;
this.vy = Math.random() * -15 - 5;
this.gravity = 0.3;
this.opacity = 1;
this.sparks = [];
this.sparkCount = Math.random() * 20 + 80;
this.exploded = false;
}
update() {
if (!this.exploded) {
this.x += this.vx;
this.y += this.vy;
this.vy += this.gravity;
if (this.vy >= 0) {
this.explode();
}
} else {
for (var i = 0; i < this.sparkCount; i++) {
this.sparks[i].update();
}
this.opacity -= 0.02;
if (this.opacity <= 0) return true;
}
}
draw() {
ctx.beginPath();
if (!this.exploded) {
ctx.arc(this.x, this.y, 3, 0, Math.PI * 2);
ctx.fillStyle = this.color;
} else {
for (var i = 0; i < this.sparkCount; i++) {
this.sparks[i].draw();
}
}
ctx.closePath();
ctx.fill();
}
explode() {
this.exploded = true;
for (var i = 0; i < this.sparkCount; i++) {
var spark = new Spark(this.x, this.y, this.color);
this.sparks.push(spark);
}
}
}
// 创建火花类
class Spark {
constructor(x, y, color) {
this.x = x;
this.y = y;
this.color = color;
this.vx = Math.random() * 5 - 2.5;
this.vy = Math.random() * 5 - 2.5;
this.opacity = 1;
}
update() {
this.x += this.vx;
this.y += this.vy;
this.opacity -= 0.02;
if (this.opacity <= 0) return true;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, 2, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.closePath();
ctx.fill();
}
}
// 随机生成颜色
function randomColor() {
var colors = ['#f03c69', '#2f80ed', '#4a69bd', '#18ce0f', '#fecd1a', '#f1c40f', '#e84118'];
return colors[Math.floor(Math.random() * colors.length)];
}
// 存储烟花实例
var fireworks = [];
// 创建烟花
function createFirework() {
var fireworksCount = Math.random() * 10 + 5;
for (var i = 0; i < fireworksCount; i++) {
var firework = new Firework();
fireworks.push(firework);
}
}
// 更新和绘制烟花
function updateAndDrawFireworks() {
ctx.clearRect(0, 0, width * resolution, height * resolution);
for (var i = 0; i < fireworks.length; i++) {
fireworks[i].update();
fireworks[i].draw();
if (fireworks[i].opacity <= 0) {
fireworks.splice(i, 1);
i--;
}
}
}
// 使用 requestAnimationFrame 持续绘制动画
function animate() {
requestAnimationFrame(animate);
createFirework();
updateAndDrawFireworks();
}
animate();
// 监听窗口大小改变事件,更新画布大小
window.addEventListener('resize', function() {
setCanvasSize();
});
这段代码使用了 Canvas 绘图技术,创建了烟花和火花两个类,通过循环绘制和更新烟花实例和火花实例来实现烟花效果。在窗口大小改变时,会自适应调整画布大小。 你可以将上述代码复制到一个 HTML 文件中进行测试。