I've got a background div where stars (as in the universe) are placed at random places and with random width and height. Now I want to have a lot of stars at the top of the page and the further you get from the top of the page, I want there to be less stars. So I probably want to decrease a JS variable. I've already tried creating separate divs which each contain less stars, but the gaps between the divs are slightly noticeable.
This function will scatter the Star.svg throughout the whole div, but I want the amount of stars to decrease gradually when nearing the end of the div at the bottom.
Example of the function:

<div id="stars1"></div> <!-- this div is 100vh -->
funtion starGen() {
var amount1 = Math.floor(Math.random() * 100) 5;
var divWidth = document.getElementById("stars1").clientWidth - 30;
var divHeight = document.getElementById("stars1").clientHeight - 30;
for (let i = 0; i < amount1; i ) {
var img = document.createElement("img");
var top = Math.floor(Math.random() * divHeight);
var right = Math.floor(Math.random() * divWidth);
img.src = "./assets/img/Star 6.svg";
img.height = Math.floor(Math.random() * 25) 5;
img.width = 20;
img.style.position = "absolute";
img.style.top = top "px";
img.style.left = right "px";
document.getElementById("stars1").appendChild(img);
}
CodePudding user response:
Explanation:
Math.random() will generate a random set of numbers that are uniformly distributed. This is fine for the right position of stars, but for the top position of stars you want an exponentially distributed set of numbers that make more common occurrences at the top.
Generated example:
Code:
Source: https://jsfiddle.net/tvmgs37w/
Excerpt:
function starGen() {
var amountOfStars = Math.floor(Math.random() * 100) 5;
var divWidth = document.getElementById("starrySky").clientWidth - 30;
var divHeight = document.getElementById("starrySky").clientHeight - 30;
for (let i = 0; i < amountOfStars; i ) {
var star = document.createElement("div");
var top = Math.floor(randomExponential() * divHeight);
var right = Math.floor(Math.random() * divWidth);
star.textContent = "*";
star.height = Math.floor(Math.random() * 25) 5;
star.width = 20;
star.style.position = "absolute";
star.style.top = top "px";
star.style.left = right "px";
star.style.color = "yellow";
document.getElementById("starrySky").appendChild(star);
}
}
function randomExponential() {
var u = Math.random();
var mu = 1.5;
return -Math.log(1.0 - u) / mu;
}
starGen();
<div id="starrySky" style="width:100vw; height:100vh;background-color:darkblue"></div> <!-- this div is 100vh -->
