-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathstarfield.js
57 lines (51 loc) · 1.41 KB
/
starfield.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
import { transition, randomBetween } from "./helpers/helpers.js";
export const makeStarfield = (state) => {
const CTX = state.get("CTX");
const canvasWidth = state.get("canvasWidth");
const canvasHeight = state.get("canvasHeight");
const theme = state.get("theme");
let stars = [];
const randomNoise = (amount) => {
let noiseArray = [];
for (let index = 0; index < amount; index++) {
noiseArray.push({
opacity: randomBetween(0.1, 1),
position: {
x: Math.random() * canvasWidth,
y: randomBetween(0, canvasHeight),
},
distance: Math.random(), // higher number is closer/bigger
});
}
return noiseArray;
};
const reGenerate = () => {
stars = randomNoise((canvasWidth * canvasHeight) / 6000);
};
reGenerate();
const draw = (velocity) => {
stars.forEach(({ distance, opacity, position }) => {
position.y =
position.y > canvasHeight
? 0
: position.y < 0
? canvasHeight
: position.y - (velocity.y * distance) / 10;
CTX.save();
CTX.globalAlpha = opacity;
CTX.fillStyle = state.get("theme").star;
CTX.beginPath();
CTX.arc(
position.x,
position.y,
transition(0.2, 1.5, distance),
0,
Math.PI * 2
);
CTX.closePath();
CTX.fill();
CTX.restore();
});
};
return { draw, reGenerate };
};