function updateLabel(label, tx, ty) { label.left += tx; label.cx += tx; label.right += tx; label.top += ty; label.cy += ty; label.bottom += ty; } function colision(a, b) { return a.left < b.right && a.right > b.left && a.top < b.bottom && a.bottom > b.top; } // based on http://bl.ocks.org/larskotthoff/11406992 function arrangeLabels(labels, module, loops) { var move = true; module /= labels.length; while (move && loops--) { move = false; labels.forEach(function (a) { labels.forEach(function (b) { if (b !== a) { if (colision(a, b)) { move = true; updateLabel(b, -module * Math.sign(a.cx - b.cx), -module * Math.sign(a.cy - b.cy)); updateLabel(a, module * Math.sign(a.cx - b.cx), module * Math.sign(a.cy - b.cy)); } } }); }); } } function addMargin(label, margin) { label.left -= margin; label.right += margin; label.top -= margin; label.bottom += margin; label.width += 2 * margin; label.height += 2 * margin; }