File size: 1,586 Bytes
68eb063 bd2551d 68eb063 d5e4f71 68eb063 bd2551d 68eb063 bd2551d 68eb063 bd2551d 68eb063 bd2551d 68eb063 |
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 |
const canvas = document.getElementById("starfield");
const ctx = canvas.getContext("2d");
let stars = [];
function resizeCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
function createStars(count) {
stars = [];
for (let i = 0; i < count; i++) {
stars.push({
x: Math.random() * canvas.width - canvas.width / 2,
y: Math.random() * canvas.height - canvas.height / 2,
z: Math.random() * canvas.width,
});
}
}
function moveStars() {
const speed = 4; // speed
for (let i = 0; i < stars.length; i++) {
stars[i].z -= speed;
if (stars[i].z <= 0) {
stars[i].z = canvas.width;
stars[i].x = Math.random() * canvas.width - canvas.width / 2;
stars[i].y = Math.random() * canvas.height - canvas.height / 2;
}
}
}
function drawStars() {
ctx.fillStyle = "black";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "white";
for (let i = 0; i < stars.length; i++) {
const k = 128.0 / stars[i].z;
const x = stars[i].x * k + canvas.width / 2;
const y = stars[i].y * k + canvas.height / 2;
if (x >= 0 && x <= canvas.width && y >= 0 && y <= canvas.height) {
const size = (1 - stars[i].z / canvas.width) * 2;
ctx.beginPath();
ctx.arc(x, y, size, 0, Math.PI * 2);
ctx.fill();
}
}
}
function animate() {
moveStars();
drawStars();
requestAnimationFrame(animate);
}
window.addEventListener("resize", () => {
resizeCanvas();
createStars(1000); // Double the star count
});
resizeCanvas();
createStars(1000);
animate();
|