JSFiddle - React, Tailwind, and code Playground
HTML
<div id="container">
</div>
<input id="add" type="button" value="Add"/>
<input id="move" type="button" value="Move"/>
CSS
#container {
background: antiquewhite;
width: 700px;
height: 500px;
}
.box {
position: absolute;
background: aquamarine;
border: 1px solid gray;
}
.movedBox {
position: absolute;
background: darksalmon;
}
.overlapped {
background: red;
opacity: 0.8;
}
.ghost {
background: transparent;
border: 1px dashed black;
position: absolute;
}
JavaScript
$(function() {
var container = $("#container");
function BoxList() {
var self = this;
var boxes = [];
self.add = function(item, iteration) {
// check intersections with existing boxes
iteration = iteration || 0;
if (iteration < 5) {
for (var i=0; i < boxes.length; i++) {
if (doesIntersect(getBounds(item),getBounds(boxes[i]))) {
item.elem.addClass("overlapped");
// move item
var ghost = $("<div>");
ghost.offset(item.elem.offset());
ghost.width(item.elem.width());
ghost.height(item.elem.height());
ghost.addClass("ghost");
container.append(ghost);
// Find vector from mid point of one box to the other
var centerA = { x: item.x + item.width / 2, y: item.y + item.height / 2 };
var centerB = { x: boxes[i].x + boxes[i].width / 2, y: boxes[i].y + boxes[i].height / 2 };
var line = { x1 : centerA.x, y1 : centerA.y, x2 : centerB.x, y2 : centerB.y };
//var vector = { x : line.x1 - line.x2, y: line.y1 - line.y2 };
var box1 = item, box2 = boxes[i];
var vector = {
x: Math.min(box1.x + box2.width, box2.x + box2.width) - Math.max(box1.x, box2.x),
y: Math.min(box1.y + box2.height, box2.y + box2.height) - Math.max(box1.y, box2.y)
};
console.log(vector);
item.x = item.x + vector.x;
item.y = item.y + vector.y;
item.elem.offset({ left: item.x , top: item.y }); // TODO: calculate size of move needed
return self.add(item, iteration + 1);
}
}
}
boxes.push(item);
}
function getBounds(item) {
return { x1: item.x, x2: item.x + item.width, y1: item.y, y2: item.y + item.height };
}
function doesIntersect(a,b) {
return a.x1 < b.x2 && a.x2 > b.x1 && a.y1 < b.y2 && a.y2 >...