-
Notifications
You must be signed in to change notification settings - Fork 0
/
stars.js
96 lines (75 loc) · 1.9 KB
/
stars.js
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// Liberated from https://medium.com/better-programming/fun-with-html-canvas-lets-create-a-star-field-a46b0fed5002
const canvas = document.getElementById("canvas");
const c = canvas.getContext("2d");
let w;
let h;
const setCanvasExtents = () => {
w = document.body.clientWidth;
h = document.body.clientHeight;
canvas.width = w;
canvas.height = h;
};
setCanvasExtents();
window.onresize = () => {
setCanvasExtents();
};
const makeStars = count => {
const out = [];
for (let i = 0; i < count; i++) {
const s = {
x: Math.random() * 1600 - 800,
y: Math.random() * 900 - 450,
z: Math.random() * 1000
};
out.push(s);
}
return out;
};
let stars = makeStars(5000);
const clear = () => {
c.fillStyle = "black";
c.fillRect(0, 0, canvas.width, canvas.height);
};
const putPixel = (x, y, brightness) => {
const intensity = brightness * 255;
const rgb = "rgb(" + intensity + "," + intensity + "," + intensity + ")";
c.fillStyle = rgb;
c.fillRect(x, y, 2, 2);
};
const moveStars = distance => {
const count = stars.length;
for (var i = 0; i < count; i++) {
const s = stars[i];
s.z -= distance;
while (s.z <= 1) {
s.z += 1000;
}
}
};
let prevTime;
const init = time => {
prevTime = time;
requestAnimationFrame(tick);
};
const tick = time => {
let elapsed = time - prevTime;
prevTime = time;
moveStars(elapsed * 0.07);
clear();
const cx = w / 2;
const cy = h / 2;
const count = stars.length;
for (var i = 0; i < count; i++) {
const star = stars[i];
const x = cx + star.x / (star.z * 0.001);
const y = cy + star.y / (star.z * 0.001);
if (x < 0 || x >= w || y < 0 || y >= h) {
continue;
}
const d = star.z / 1000.0;
const b = 1 - d * d;
putPixel(x, y, b);
}
requestAnimationFrame(tick);
};
requestAnimationFrame(init);