点击按钮时请点击我!如何避免随机数重叠? 它会生成随机数,但有一些数字是重叠的,如何避免这种情况...,这里我不是在谈论随机数的重复,我想避免随机数的重叠...
const circle = document.querySelector(".circle");
const addNumBtn = document.querySelector('#addNumBtn')
function randomValue() {
let random = Math.floor(Math.random() * 50) + 1;
return random;
}
function randomColor(){
let r = Math.floor(Math.random() * 255) + 1;
let g = Math.floor(Math.random() * 255) + 1;
let b = Math.floor(Math.random() * 255) + 1;
return `rgba(${r},${g},${b})`
}
function randomSize(){
let size = Math.floor(Math.random() * 30) + 8;
return `${size}px`
}
function randNum() {
let randnum = document.createElement("p");
randnum.classList.add('numStyle')
randnum.style.color=randomColor();
randnum.style.fontSize=randomSize();
randnum.textContent = randomValue();
randnum.style.position = 'absolute'
randnum.style.top = `${randomValue()}px`
randnum.style.left = `${randomValue()}px`
randnum.style.bottom = `${randomValue()}px`
randnum.style.right = `${randomValue()}px`
circle.append(randnum);
}
addNumBtn.addEventListener('click',randNum)
.circle {
aspect-ratio: 1;
width: 300px;
background-color: black;
border-radius: 50%;
position: relative;
overflow:hidden;
}
#addNumBtn{
position:absolute;
top:0;
left:0;
}
.numStyle{
font-family:"roboto",sans-serif;
}
//On Clicking button Click Me! I want to place all the random numbers inside the circle
//together not one by one, at a time all numbers should be placed inside the circle by
//clicking
the button Click Me!
<div id="container"></div>
<div class="circle"></div>
</div>
<button id="addNumBtn">Click Me!</button>
最佳答案
您需要循环随机数生成器,达到您希望在圆圈中显示创建的数字元素的次数。您可以在 randomValue()
函数中创建并返回值的数组,然后在 randNum()
函数中循环遍历该数组。
另外,我假设您希望附加元素的输出分布在整个圆形元素上,是吗?如果是这样,您需要随机化元素相对于圆的大小的位置,而不是 randomValue
函数返回的值。
编辑:
OP在发布答案后询问:圆圈边框一侧有一些数字无法正确显示,如何解决?
由于元素的盒模型,圆形元素的边框是方形的,而不是圆形的,尽管圆形元素的可视内容由于其border-radius css而呈圆形。
您可以使用辅助函数来确定 x 和 y 或 left 和 top 的随机生成数字,位于圆形元素的border-radius
内,使用半径的大小和中心点 圆的 x 和 y 坐标。
辅助函数的功劳: Simon Sarris :
function pointInCircle(x, y, cx, cy, rad) {
const distancesquared = (x - cx) * (x - cx) + (y - cy) * (y - cy);
return distancesquared <= rad * rad;
}
我们将所有内容包装在 while 循环中,检查计数器是否已达到 50。在循环内,我们运行创建随机生成位置的函数 -> randomPos()
。然后我们运行一个条件,使用函数pointInCircle(x, y, cx, cy, rad)检查随机生成的点是否在圆内。如果此条件返回 true,我们将创建数字元素、样式并将数字元素附加到圆圈中,并将计数器值迭代 1。
const circle = document.querySelector(".circle");
const addNumBtn = document.querySelector('#addNumBtn');
// we set the width of the circle element in JS and pass
// it to CSS using a css variable and the root element
const circleWidth = 350;
document.documentElement.style.setProperty('--circleWidth', `${circleWidth}px`);
// NOTE: '~~' -> is quicker form of writing Math.floor()
// runs faster on most browsers.
function randomPos(min, max) {
return ~~(Math.random() * (max - min + 1) + min)
}
// return a random value between 1 and 50
function randomValue(){
return ~~(Math.random() * 50) + 1;
}
function randomColor() {
let r = ~~(Math.random() * 255) + 1;
let g = ~~(Math.random() * 255) + 1;
let b = ~~(Math.random() * 255) + 1;
return `rgba(${r},${g},${b})`
}
function randomSize() {
let size = ~~(Math.random() * 30) + 8;
return `${size}px`
}
// add a helper function to find the center of the
// circle and calculate distance to the edge of circle
// x and y are the randomly generated points
// cx, cy are center of circle x and y repsectively
// rad is circle radius
function pointInCircle(x, y, cx, cy, rad) {
const distancesquared = (x - cx) * (x - cx) + (y - cy) * (y - cy);
return distancesquared <= rad * rad;
}
// you can remove valArray array if you do not want the 50 numbers to not be repeated
const valArray = [];
function randNum() {
// add a counter
let count = 1;
// while loop to check if the counter has reached the target 50
while (count <= 50) {
// set the randomly generated val
let val = randomValue();
// random size = string with px added
let randSize = randomSize();
// random size = the exact number => typeof number
let posSize = randSize.split('px')[0];
// an array to hold our randomly positioned number values
// uses helper function randonPos
// pass in the 1 and the circle width minus the font size
let ran = [randomPos(1, circleWidth - posSize), randomPos(1, circleWidth - posSize)];
// conditional to check bounds of circle using helper function
// we pass in the ran array, center points and radius
// we add buffers to accommodate for the font size
// you can remove !valArray.includes(val) if you do not want the 50 numbers to not be repeated
if (pointInCircle(ran[0], ran[1], circleWidth/2-posSize, circleWidth/2-posSize, circleWidth / 2 - posSize) && !valArray.includes(val)) {
// you can remove valArray.push(val); if you do not want the 50 numbers to not be repeated
valArray.push(val);
// if the conditional returns true,
// create the element, style and append
let randnum = document.createElement("p");
randnum.classList.add('numStyle');
randnum.style.color = randomColor();
randnum.style.fontSize = randSize;
randnum.textContent = val;
randnum.style.position = 'absolute';
randnum.style.top = `${ran[0]}px`;
randnum.style.left = `${ran[1]}px`;
circle.append(randnum);
// iterate the counter
count++;
}
}
}
addNumBtn.addEventListener('click', randNum)
html {
--circle-width: 300px;
}
.circle {
aspect-ratio: 1;
width: var(--circleWidth);
background-color: black;
border-radius: 50%;
position: relative;
overflow: hidden;
padding: .5rem;
}
#addNumBtn {
position: absolute;
top: 0;
left: 0;
}
.numStyle {
font-family: "roboto", sans-serif;
}
//On Clicking button Click Me! I want to place all the random numbers inside the circle //together not one by one, at a time all numbers should be placed inside the circle by //clicking the button Click Me!
<div id="container"></div>
<div class="circle">
</div>
<button id="addNumBtn">Click Me!</button>
关于javascript - 如何避免随机数重叠?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71010672/