js实现星空
实现星空效果的JavaScript代码
以下是一个使用HTML5 Canvas和JavaScript创建星空动画效果的示例代码。该代码会生成随机分布的星星,并模拟闪烁和移动效果。
<!DOCTYPE html>
<html>
<head>
<title>JavaScript星空效果</title>
<style>
body {
margin: 0;
overflow: hidden;
background-color: #000;
}
canvas {
display: block;
}
</style>
</head>
<body>
<canvas id="starfield"></canvas>
<script>
const canvas = document.getElementById('starfield');
const ctx = canvas.getContext('2d');
// 设置画布大小为窗口大小
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// 星星数组
const stars = [];
const starCount = 500; // 星星数量
// 星星类
class Star {
constructor() {
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
this.size = Math.random() * 1.5;
this.speed = Math.random() * 0.2;
this.opacity = Math.random();
this.opacityChange = Math.random() * 0.02;
}
update() {
this.y += this.speed;
this.opacity += this.opacityChange;
// 如果星星移出屏幕底部,重置到顶部
if (this.y > canvas.height) {
this.y = 0;
this.x = Math.random() * canvas.width;
}
// 反转透明度变化方向
if (this.opacity > 1 || this.opacity < 0) {
this.opacityChange = -this.opacityChange;
}
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fillStyle = `rgba(255, 255, 255, ${this.opacity})`;
ctx.fill();
}
}
// 初始化星星
for (let i = 0; i < starCount; i++) {
stars.push(new Star());
}
// 动画循环
function animate() {
ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (const star of stars) {
star.update();
star.draw();
}
requestAnimationFrame(animate);
}
// 窗口大小改变时重置画布
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
animate();
</script>
</body>
</html>
代码说明
-
Canvas设置
- 创建全屏Canvas元素
- 获取2D渲染上下文
- 监听窗口大小变化并调整Canvas尺寸
-
星星类(Star)
- 随机生成星星的初始位置(x,y)
- 随机设置星星大小、速度和初始透明度
- 实现星星下落和透明度变化动画
-
动画循环

- 使用半透明黑色矩形覆盖实现拖尾效果
- 更新并绘制所有星星
- 使用requestAnimationFrame实现平滑动画
自定义选项
可以通过修改以下参数来自定义星空效果:
// 星星数量(默认500)
const starCount = 800;
// 星星最大尺寸(默认1.5)
this.size = Math.random() * 3;
// 星星下落速度(默认0.2)
this.speed = Math.random() * 0.5;
// 透明度变化速度(默认0.02)
this.opacityChange = Math.random() * 0.05;
进阶优化
-
添加流星效果 可以扩展代码,随机生成从屏幕一侧飞向另一侧的流星。

-
不同颜色的星星 修改fillStyle,使用HSL颜色空间实现多彩星空:
ctx.fillStyle = `hsla(${Math.random()*360}, 100%, 50%, ${this.opacity})`; -
视差效果 创建不同速度的多层星星,模拟深度感。
-
交互效果 监听鼠标移动事件,使星星产生避让效果。






