const canvas = document.getElementById('starrySky'); const ctx = canvas.getContext('2d'); // 设置canvas尺寸以填充整个视口 canvas.width = window.innerWidth; canvas.height = window.innerHeight; // 粒子数组 const particles = []; const numParticles = 150; // 粒子数量 const maxRadius = 5; // 最大半径 const minRadius = 2; // 最小半径 const speedFactor = 0.5; // 速度因子,控制粒子移动速度 // 创建粒子类 class Particle { constructor(x, y, radius, color) { this.x = x; this.y = y; this.radius = radius; this.color = color; this.speedX = Math.random() * speedFactor - speedFactor / 2; // 随机x轴速度 this.speedY = Math.random() * speedFactor - speedFactor / 2; // 随机y轴速度 } draw() { ctx.beginPath(); ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false); ctx.fillStyle = this.color; ctx.fill(); } update() { this.x += this.speedX; this.y += this.speedY; if (this.x + this.radius > canvas.width || this.x - this.radius < 0) { this.speedX *= -1; // 碰到边缘反弹 } if (this.y + this.radius > canvas.height || this.y - this.radius < 0) { this.speedY *= -1; // 碰到边缘反弹 } } } // 初始化粒子数组 function initParticles() { for (let i = 0; i < numParticles; i++) { const x = Math.random() * canvas.width; const y = Math.random() * canvas.height; const radius = Math.random() * (maxRadius - minRadius) + minRadius; // 随机半径大小 const color = `rgba(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255}, ${Math.random()})`; // 随机颜色和透明度 particles.push(new Particle(x, y, radius, color)); } } // 动画循环函数 function animate() { ctx.clearRect(0, 0, canvas.width, canvas.height); // 清除画布,重新绘制粒子 particles.forEach(particle => { particle.update(); // 更新粒子位置和速度 particle.draw(); // 绘制粒子到画布上 }); requestAnimationFrame(animate); // 请求下一帧动画,实现平滑动画效果 } // 初始化并开始动画循环 initParticles(); animate();