jQuery 是一个快速、小巧且功能丰富的 JavaScript 库,它简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。自动烟花特效是一种视觉效果,通常用于庆祝、节日或其他特殊场合,通过模拟烟花绽放的过程来吸引用户的注意力。
以下是一个简单的 jQuery 自动烟花特效示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery 烟花特效</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
display: block;
}
</style>
</head>
<body>
<canvas id="fireworks"></canvas>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
const canvas = document.getElementById('fireworks');
const ctx = canvas.getContext('2d');
let width = canvas.width = window.innerWidth;
let height = canvas.height = window.innerHeight;
class Particle {
constructor(x, y) {
this.x = x;
this.y = y;
this.radius = Math.random() * 3 + 1;
this.color = `hsl(${Math.random() * 360}, 70%, 50%)`;
this.speedX = Math.random() * 4 - 2;
this.speedY = Math.random() * 4 - 2;
this.opacity = 1;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.globalAlpha = this.opacity;
ctx.fill();
}
update() {
this.x += this.speedX;
this.y += this.speedY;
this.opacity -= 0.01;
this.radius -= 0.1;
this.draw();
}
}
function createFirework() {
const x = Math.random() * width;
const y = height;
for (let i = 0; i < 100; i++) {
particles.push(new Particle(x, y));
}
}
let particles = [];
setInterval(() => {
ctx.clearRect(0, 0, width, height);
particles.forEach((particle, index) => {
particle.update();
if (particle.opacity <= 0) {
particles.splice(index, 1);
}
});
if (particles.length === 0) {
createFirework();
}
}, 16);
createFirework();
});
</script>
</body>
</html>
通过以上方法,可以实现一个简单的 jQuery 自动烟花特效,并解决可能遇到的问题。