我有一個背景 div,其中星星(如在宇宙中)被放置在隨機的位置,并且具有隨機的寬度和高度。現在我希望在頁面頂部有很多星星,并且離頁面頂部越遠,我希望星星越少。所以我可能想減少一個 JS 變數。我已經嘗試過創建單獨的 div,每個 div 包含的星數較少,但 div 之間的差距有點明顯。
這個函式會將 Star.svg 分散在整個 div 中,但我希望在接近底部 div 的末尾時星星的數量逐漸減少。函式示例:

<div class="stars1" 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);
}
uj5u.com熱心網友回復:
解釋:
Math.random() 將生成一組均勻分布的亂數字。這對于星星的正確位置很好,但對于星星的頂部位置,您需要一組指數分布的數字,這些數字在頂部出現更常見的情況。
生成的例子:
生成的星空
代碼:
來源:https ://jsfiddle.net/tvmgs37w/
摘抄:
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 class="starrySky" id="starrySky" style="width:100vw; height:100vh;background-color:darkblue"></div> <!-- this div is 100vh -->
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/411380.html
標籤:
上一篇:在1行中顯示表格
