Random dot generator
Bad performance 20 is max
by levchenko_d
HTML
<div class="area">
<div class="safe-area">
</div>
</div>
<p>Scipt eveluted <strong class="sevres">0</strong> time(s)</p>
CSS
body{
margin: 0;
}
.area{
position: relative;
background: blue;
height: 400px;
}
.safe-area{
position: relative;
top: 100px;
left: 100px;
background: silver;
height: 200px;
width: calc(100% - 200px);
}
i{
position: absolute;
width: 10px;
height: 10px;
background: red;
border-radius: 50%;
}
JavaScript
var evaluated = 0;
var storage = [];
function getLocation(el){
var position = $(el).position();
return {
x: position.left,
y: position.top,
x1: position.left + $(el).width(),
y1: position.top + $(el).height()
};
}
function isInBounds(l1, l2){
return (l1.x >= l2.x &&
l1.x <= l2.x1 &&
l1.x1 >= l2.x &&
l1.x1 <= l2.x1 &&
l1.y >= l2.y &&
l1.y <= l2.y1 &&
l1.y1 >= l2.y &&
l1.y1 <= l2.y1);
}
function isOutOfBounds(l1, l2){
var isOutX = true,
isOutY = true;
if(l1.x <= l2.x){
isOutX = l1.x1 <= l2.x;
} else if (l1.x >= l2.x1 || l1.y >= l2.y){
isOutX = true;
} else {
isOutX = false;
}
if(l1.y <= l2.y){
isOutY = l1.y1 <= l2.y
} else if(l1.y >= l2.y1 || l1.x >= l2.x1){
isOutY = true;
} else {
isOutY = false;
}
return isOutX && isOutY;
}
function notOverlapingElements(l1){
var size = storage.length,
count = 0;
console.count('here');
function next(){
var l2 = storage[count].location,
isOut = isOutOfBounds(l1, l2);
count++;
if(!isOut){
return false;
} else if(count < size){
return next();
} else {
return true;
}
}
if(size === 0){
return true;
} else {
return next();
}
}
function testLocation(l1, l2, l3){
var isInArea = isInBounds(l1, l2),
isOutOfSafe = isOutOfBounds(l1, l3),
isNotOverlapingElements = notOverlapingElements(l1);
return isInArea && isOutOfSafe && isNotOverlapingElements;
}
function generateLocation(el, areaLoc){
var x = Math.floor(Math.random() * (areaLoc.x1-areaLoc.x) + areaLoc.x),
y = Math.floor(Math.random() * (areaLoc.y1-areaLoc.y) + areaLoc.y),
w = $(el).width(),
h = $(el).height();
evaluated++;
$('.sevres').text(evaluated);
return {
x: x,
y: y,
x1: x+w,
y1: y+h
};
}
function draw(){
var i = document.createElement('i'),
areaLoc = getLocation($('.area')),
safeLoc...