Reputation: 1564
Idea is very simple, imagine that you have any rectangle and you want to roll random point on its border, i have accomplished that by doing this:
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>
So now when i have a random point an a rectangle i need to also assign 3 remaining corresponding points like this:
I tried to do this using couple of approaches but none of them seem to work correctly, does anyone have an idea how to get remaining 3 points based on one that i have?
Upvotes: 0
Views: 65
Reputation: 4106
You need to generate a random number between 0 and Math.min(width, height)
. Let's call this random number d
. From there, the coordinates of your points within the rectangle are as follows:
d, 0
width, d
width - d, height
0, height - d
You just need to apply this principle to your implementation.
Upvotes: 1