-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathstars.js
82 lines (70 loc) · 2.27 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
let animationFrameId;
export function starAnimation() {
const canvas = document.getElementById("starCanvas");
const ctx = canvas.getContext("2d");
const starCount = 150;
const stars = [];
const centerX = window.innerWidth / 2;
const centerY = window.innerHeight / 2;
function setupCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
function createStars() {
for (let i = 0; i < starCount; ++i) {
const angle = Math.random() * 2 * Math.PI;
const radius = Math.random() * Math.max(window.innerWidth, window.innerHeight) * 1.5;
stars.push({
x: centerX + radius * Math.cos(angle),
y: centerY + radius * Math.sin(angle),
radius: Math.random() * 2 + 0.5,
speed: Math.random() * 3 + 0.5,
opacity: 1
});
}
}
function resetStar(star) {
const angle = Math.random() * 2 * Math.PI;
const radius = Math.random() * Math.max(window.innerWidth, window.innerHeight) * 1.5;
star.x = centerX + radius * Math.cos(angle);
star.y = centerY + radius * Math.sin(angle);
star.radius = Math.random() * 2 + 0.5;
star.speed = Math.random() * 3 + 0.5;
star.opacity = 1;
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
stars.forEach((star) => {
const dx = centerX - star.x;
const dy = centerY - star.y;
const distance = Math.sqrt(dx * dx + dy * dy);
if (distance < 5) {
resetStar(star);
} else {
star.x += (dx / distance) * star.speed;
star.y += (dy / distance) * star.speed;
star.speed+=0.009
}
const maxDistance = Math.max(window.innerWidth, window.innerHeight) / 2 + 50;
star.opacity = Math.min(distance / maxDistance, 1);
ctx.beginPath();
ctx.arc(star.x, star.y, star.radius, 0, Math.PI * 2);
ctx.fillStyle = `rgba(250, 250, 250, ${star.opacity})`;
ctx.fill();
});
animationFrameId = window.requestAnimationFrame(animate);
}
setupCanvas();
createStars();
animate();
}
export function killAll() {
const canvas = document.getElementById("starCanvas");
if (animationFrameId) {
cancelAnimationFrame(animationFrameId);
animationFrameId = null;
}
if (canvas) {
canvas.parentNode.removeChild(canvas);
}
}