JSFiddle - React, Tailwind, and code Playground
by ElijahCirioli
HTML
<body>
<div id=starfield>
<span id=star class=star></span>
</div>
</body>
CSS
body {
background-color: #000;
width: 100vw;
height: 1000px;
overflow: hidden;
}
#starfield {
width: 100%;
height: 100vh;
overflow: hidden;
}
.star {
background: rgb(255, 255, 255);
background: radial-gradient(circle, rgba(255,255,255,1) 0%, rgba(183,185,184,1) 20%, rgba(4,13,9,1) 50%);
border-radius: 50%;
display: inline-block;
position: absolute;
}
JavaScript
const starfield = document.getElementById("starfield");
const og_star = document.getElementById("star");
let stars = [];
let height = starfield.offsetHeight;
let width = starfield.offsetWidth;
function createStar(x, y, size) {
let new_star = og_star.cloneNode();
new_star.style.left = x - size / 2 + "px";
new_star.style.top = y - size / 2 + "px";
new_star.style.height = size + "px";
new_star.style.width = size + "px";
new_star.style.opacity = Math.random();
starfield.appendChild(new_star);
stars.push(new_star);
}
/* function fadeStarTo(star, target, duration) {
if (!star.style.opacity) {
star.style.opacity = 1;
}
let steps = Math.abs(target - parseFloat(star.style.opacity)) * 100;
var fadeEffect = setInterval(function() {
if (star.style.opacity > target + 0.005) {
star.style.opacity -= 0.01;
} else if (star.style.opacity < target - 0.005) {
star.style.opacity = parseFloat(star.style.opacity) + 0.01;
} else {
clearInterval(fadeEffect);
}
}, duration / steps);
} */
function randomMap(x) {
return Math.exp(6.5 * (1 - 1 / x)) + 0.01;
}
function generateStars(boxX, boxY, boxWidth, boxHeight) {
let starcount = boxWidth * boxHeight / 1000;
for (let i = 0; i < starcount; i++) {
let size = Math.max(8 * randomMap(Math.random()), 0.5);
let x = Math.random() * boxWidth- size / 2 + boxX;
let y = Math.random() * boxHeight - size / 2 + boxY;
createStar(x, y, size);
}
}
function resizeCheck() {
newHeight = starfield.offsetHeight;
newWidth = starfield.offsetWidth;
if (newWidth > width)
generateStars(width, 0, newWidth - width, newHeight)
if (height > oldheight)
generateStars(0, height, width, newHeight - height)
height = newHeight;
width = newWidth;
}
generateStars(0, 0, width, height);
window.onresize = resizeCheck;
/* var twinkle = setInterval(function() {
for (var i = 0; i < stars.length; i++) {
if (Math.random() < 0.6) continue;
star =...