想法很简单,想象你有任何矩形,你想在它的边界上滚动随机点,我已经完成了这样做:
var width = 300,
height = 200,
margin = 0;
var rnd = function(min, max) {
return Math.floor(Math.random() * (Math.floor(max) - Math.ceil(min) + 1)) + Math.ceil(min);
};
var point = rnd(0, (width * 2) + (height * 2));
var points = [
{ x: 0, y: 0 },
{ x: 0, y: 0 },
{ x: 0, y: 0 },
{ x: 0, y: 0 }
]
var set_point = function(point) {
var coords = { x: 0, y: 0 };
if(point <= width) { // if on top
coords.x = point;
coords.y = -margin;
} else if(point <= width + height) { // if on the right
coords.x = width + margin;
coords.y = point - width;
} else if(point <= (width * 2) + height) { // if on the bottom
coords.x = ((width * 2) + height) - point;
coords.y = height + margin;
} else { // if on the left
coords.x = -margin;
coords.y = ((width * 2) + (height * 2)) - point;
}
return coords;
};
var test = set_point(point);
points[0].x = test.x;
points[0].y = test.y;
for(var i = 0; i < 1 /*points.length*/; i++) {
var dot = document.createElement('div');
dot.className = 'point';
dot.style.left = points[i].x + 'px';
dot.style.top = points[i].y + 'px';
document.querySelector('.rect').appendChild(dot);
}
.rect {
border:solid 1px #000;
width:300px;
height:200px;
position:absolute;
top:calc(50% - 100px);
left:calc(50% - 150px);
}
.point {
width:10px;
height:10px;
position:absolute;
border-radius:100%;
border:solid 1px red;
background:red;
transform:translate3d(-5px, -5px, 0);
}
<div class="rect"></div>
所以现在当我有一个随机点一个矩形时,我还需要分配3个剩余的对应点,如下所示:
我尝试使用几种方法做到这一点,但它们似乎都没有正常工作,有没有人知道如何根据我的一个得到剩余的3分?
答案 0 :(得分:1)
您需要生成介于0和Math.min(width, height)
之间的随机数。我们称这个随机数为d
。从那里,矩形内点的坐标如下:
d, 0
width, d
width - d, height
0, height - d
您只需将此原则应用于您的实施。