canvas绘制一片星空

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
var w = window.innerWidth;
var h = window.innerHeight;
var sky = document.getElementById("sky");
var skyDraw = sky.getContext("2d");
sky.width = w;
sky.height = h;
const stars = [];
for (let i = 0; i < 100; i++) {
stars.push({
x: Math.random() * w,
y: Math.random() * h,
size: 2,
brightness: Math.random(),
speed: 0.01 + Math.random() * 0.02
});
}

setInterval(() => {
const gradient = skyDraw.createLinearGradient(0, 0, 0, h);
gradient.addColorStop(0, '#000000'); // 顶部纯黑
gradient.addColorStop(1, '#1a0033'); // 底部黑紫色
skyDraw.fillStyle = gradient;
skyDraw.fillRect(0, 0, w, h);
stars.forEach(star => {
// 星星闪烁:正弦函数实现平滑明暗变化
star.brightness += star.speed;
const alpha = 0.5 + Math.abs(Math.sin(star.brightness)) * 0.5;

// 绘制2x2黄色星星(暖黄色)
skyDraw.fillStyle = `rgba(255, 255, 200, ${alpha})`;
skyDraw.fillRect(star.x, star.y, star.size, star.size);
});
}, 10)