星空实现js
星空效果的实现方法
在JavaScript中创建星空效果通常涉及在HTML5 Canvas上绘制随机分布的星星,并添加闪烁或移动动画。以下是两种常见实现方式:
基础Canvas星空动画
const canvas = document.getElementById('starCanvas');
const ctx = canvas.getContext('2d');
// 设置canvas为全屏
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// 创建星星数组
const stars = [];
for (let i = 0; i < 500; i++) {
stars.push({
x: Math.random() * canvas.width,
y: Math.random() * canvas.height,
radius: Math.random() * 1.5,
speed: Math.random() * 0.2,
opacity: Math.random()
});
}
function animateStars() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
stars.forEach(star => {
star.y += star.speed;
if (star.y > canvas.height) {
star.y = 0;
star.x = Math.random() * canvas.width;
}
ctx.beginPath();
ctx.arc(star.x, star.y, star.radius, 0, Math.PI * 2);
ctx.fillStyle = `rgba(255, 255, 255, ${star.opacity})`;
ctx.fill();
});
requestAnimationFrame(animateStars);
}
animateStars();
使用CSS实现的星空背景
对于不需要复杂动画的简单星空效果,可以使用纯CSS:
<div class="stars"></div>
<style>
.stars {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: #000;
overflow: hidden;
}
.stars::after {
content: "";
position: absolute;
width: 1px;
height: 1px;
background: #fff;
box-shadow:
200px 100px white,
400px 300px white,
600px 200px white,
/* 添加更多星星位置 */;
animation: twinkle 5s infinite;
}
@keyframes twinkle {
0% { opacity: 0.2; }
50% { opacity: 1; }
100% { opacity: 0.2; }
}
</style>
性能优化技巧
对于大量星星的动画,使用对象池技术可以避免频繁创建和销毁对象。将星星位置计算移出渲染循环,仅在需要时更新。
考虑使用WebGL(Three.js等库)实现更复杂的星空效果,特别是需要数千颗星星或3D效果的场景。粒子系统特别适合这种视觉效果。
响应式处理
添加窗口大小变化监听,调整Canvas尺寸并重新计算星星位置:
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// 可选:重新初始化星星位置
});






