Skip to content

Instantly share code, notes, and snippets.

@aesqe
Created February 16, 2015 22:52
Show Gist options
  • Save aesqe/83551d236eb97f1b1523 to your computer and use it in GitHub Desktop.
Save aesqe/83551d236eb97f1b1523 to your computer and use it in GitHub Desktop.
rect test 1
<!DOCTYPE html>
<meta charset="utf-8">
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var width = 960,
height = 500;
var nodes = d3.range(200).map(function() { return {width: Math.random() * 20 + 10, height: Math.random() * 20 + 10}; }),
root = nodes[0],
color = d3.scale.category10();
root.radius = 0;
root.fixed = true;
var force = d3.layout.force()
.gravity(0.05)
.nodes(nodes)
.size([width, height])
.charge(function(d, i) { return i ? 0 : -2000; });
force.start();
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
svg.selectAll("rect")
.data(nodes.slice(1))
.enter().append("rect")
.attr("width", function(d) { return d.width; })
.attr("height", function(d) { return d.height; })
.style("fill", function(d, i) { return color(i); });
force.on("tick", function(e) {
var q = d3.geom.quadtree(nodes),
i = 0,
n = nodes.length;
while (++i < n) q.visit(collide(nodes[i]));
svg.selectAll("rect")
.attr("x", function(d) { return d.x; })
.attr("y", function(d) { return d.y; });
});
svg.on("mousemove", function() {
var p1 = d3.mouse(this);
root.px = p1[0];
root.py = p1[1];
force.resume();
});
function overlap(box1, box2) {
var x1min = box1.x,
y1min = box1.y,
x1max = box1.x + box1.width,
y1max = box1.y + box1.height,
x2min = box2.x,
y2min = box2.y,
x2max = box2.x + box2.width,
y2max = box2.y + box2.height;
var collision = !(x1max < x2min || x2max < x1min || y1max < y2min || y2max < y1min);
if (!collision) {
return false;
}
var overlapx = 0,
overlapy = 0,
overlapx1 = x2max - Math.max(x1min, x2min),
overlapx2 = x2min - Math.min(x1max, x2max),
overlapy1 = y2max - Math.max(y1min, y2min),
overlapy2 = y2min - Math.min(y1max, y2max);
if (Math.abs(overlapx1) < Math.abs(overlapx2)) {
overlapx = overlapx1;
} else {
overlapx = overlapx2;
}
if (Math.abs(overlapy1) < Math.abs(overlapy2)) {
overlapy = overlapy1;
} else {
overlapy = overlapy2;
}
return {
x: overlapx,
y: overlapy
};
}
function collide(node) {
var nx1 = node.x,
nx2 = node.x + node.width,
ny1 = node.y,
ny2 = node.y + node.height;
return function(quad, x1, y1, x2, y2) {
if (quad.point && (quad.point !== node)) {
var o = overlap(node, quad.point);
if (o)
{
node.x += o.x * 0.1;
node.y += o.y * 0.1;
quad.point.x -= o.x * 0.1;
quad.point.y -= o.y * 0.1;
}
}
return x1 > nx2 || x2 < nx1 || y1 > ny2 || y2 < ny1;
};
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment