Create stars.js
Browse files
stars.js
ADDED
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
const canvas = document.getElementById("starfield");
|
2 |
+
const ctx = canvas.getContext("2d");
|
3 |
+
|
4 |
+
let stars = [];
|
5 |
+
|
6 |
+
function resizeCanvas() {
|
7 |
+
canvas.width = window.innerWidth;
|
8 |
+
canvas.height = window.innerHeight;
|
9 |
+
}
|
10 |
+
|
11 |
+
function createStars(count) {
|
12 |
+
stars = [];
|
13 |
+
for (let i = 0; i < count; i++) {
|
14 |
+
stars.push({
|
15 |
+
x: Math.random() * canvas.width,
|
16 |
+
y: Math.random() * canvas.height,
|
17 |
+
z: Math.random() * canvas.width,
|
18 |
+
});
|
19 |
+
}
|
20 |
+
}
|
21 |
+
|
22 |
+
function moveStars() {
|
23 |
+
const speed = 2;
|
24 |
+
for (let i = 0; i < stars.length; i++) {
|
25 |
+
stars[i].z -= speed;
|
26 |
+
if (stars[i].z <= 0) {
|
27 |
+
stars[i].z = canvas.width;
|
28 |
+
stars[i].x = Math.random() * canvas.width;
|
29 |
+
stars[i].y = Math.random() * canvas.height;
|
30 |
+
}
|
31 |
+
}
|
32 |
+
}
|
33 |
+
|
34 |
+
function drawStars() {
|
35 |
+
ctx.fillStyle = "black";
|
36 |
+
ctx.fillRect(0, 0, canvas.width, canvas.height);
|
37 |
+
|
38 |
+
ctx.fillStyle = "white";
|
39 |
+
for (let i = 0; i < stars.length; i++) {
|
40 |
+
const k = 128.0 / stars[i].z;
|
41 |
+
const x = stars[i].x * k + canvas.width / 2;
|
42 |
+
const y = stars[i].y * k + canvas.height / 2;
|
43 |
+
|
44 |
+
if (x >= 0 && x <= canvas.width && y >= 0 && y <= canvas.height) {
|
45 |
+
const size = (1 - stars[i].z / canvas.width) * 2;
|
46 |
+
ctx.beginPath();
|
47 |
+
ctx.arc(x, y, size, 0, Math.PI * 2);
|
48 |
+
ctx.fill();
|
49 |
+
}
|
50 |
+
}
|
51 |
+
}
|
52 |
+
|
53 |
+
function animate() {
|
54 |
+
moveStars();
|
55 |
+
drawStars();
|
56 |
+
requestAnimationFrame(animate);
|
57 |
+
}
|
58 |
+
|
59 |
+
window.addEventListener("resize", () => {
|
60 |
+
resizeCanvas();
|
61 |
+
createStars(500);
|
62 |
+
});
|
63 |
+
|
64 |
+
resizeCanvas();
|
65 |
+
createStars(500);
|
66 |
+
animate();
|