要實現酷炫的粒子和流星效果,可以利用Canvas來繪制動畫。以下是一個簡單的示例代碼來實現這種效果:
<canvas id="canvas" width="800" height="600"></canvas>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let particles = [];
function createParticles() {
for (let i = 0; i < 100; i++) {
let particle = {
x: Math.random() * canvas.width,
y: Math.random() * canvas.height,
speedX: Math.random() * 4 - 2,
speedY: Math.random() * 4 - 2,
color: 'white',
size: Math.random() * 3 + 1
};
particles.push(particle);
}
}
function drawParticles() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < particles.length; i++) {
let particle = particles[i];
ctx.fillStyle = particle.color;
ctx.beginPath();
ctx.arc(particle.x, particle.y, particle.size, 0, Math.PI * 2);
ctx.fill();
particle.x += particle.speedX;
particle.y += particle.speedY;
if (particle.x > canvas.width || particle.x < 0) {
particle.speedX *= -1;
}
if (particle.y > canvas.height || particle.y < 0) {
particle.speedY *= -1;
}
}
}
function createMeteor() {
let meteor = {
x: Math.random() * canvas.width,
y: 0,
speedY: Math.random() * 4 + 2,
color: 'red',
size: Math.random() * 5 + 2
};
particles.push(meteor);
}
function draw() {
createParticles();
setInterval(() => {
createMeteor();
}, 3000);
setInterval(() => {
drawParticles();
}, 1000 / 60);
}
draw();
以上代碼會在Canvas上繪制100個白色的粒子,并且每隔3秒會在頂部生成一個紅色的流星。通過控制粒子的速度和位置,可以實現不同的效果。您可以根據需要調整代碼中的參數來實現更加酷炫的效果。