-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
74 lines (63 loc) · 1.99 KB
/
background.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
const canvas = document.getElementById("stars");
const ctx = canvas.getContext("2d");
const slider = document.querySelector(".slider input");
let screen, stars, params = {speed: 2, number: 300, extinction: 4};
setupStars();
updateStars();
slider.oninput = function () {
console.log("Slider value changed:", this.value);
params.speed = this.value;
};
// update stars on resize to keep the thing centered
window.onresize = function () {
setupStars();
};
// star constructor
function Star() {
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
this.z = Math.random() * canvas.width;
this.move = function () {
this.z -= params.speed;
if (this.z <= 0) {
this.z = canvas.width;
}
};
this.show = function () {
let x, y, rad, opacity;
x = (this.x - screen.c[0]) * (canvas.width / this.z);
x = x + screen.c[0];
y = (this.y - screen.c[1]) * (canvas.width / this.z);
y = y + screen.c[1];
rad = canvas.width / this.z;
opacity = (rad > params.extinction) ? 1.5 * (2 - rad / params.extinction) : 1;
ctx.beginPath();
ctx.fillStyle = "rgba(255, 255, 255, " + opacity + ")";
ctx.arc(x, y, rad, 0, Math.PI * 2);
ctx.fill();
}
}
// setup <canvas>, create all the starts
function setupStars() {
screen = {
w: window.innerWidth,
h: window.innerHeight,
c: [window.innerWidth * 0.5, window.innerHeight * 0.5]
};
window.cancelAnimationFrame(updateStars);
canvas.width = screen.w;
canvas.height = screen.h;
stars = [];
for (let i = 0; i < params.number; i++) {
stars[i] = new Star();
}
}
function updateStars() {
ctx.fillStyle = "black";
ctx.fillRect(0, 0, canvas.width, canvas.height);
stars.forEach(function (s) {
s.show();
s.move();
});
window.requestAnimationFrame(updateStars);
}