Spaces:
Running
Running
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(); | |