JSFiddle - React, Tailwind, and code Playground
by emepyc
HTML
<script src="http://d3js.org/d3.v3.min.js"></script>
<div id="mydiv"></div>
JavaScript
var data = [{label:"First",x:50,width:50},{label:"Second",x:50,width:50},{label:"Third",x:50,width:70},{label:"Forth",x:50,width:30},{label:"Fifth",x:120,width:90}];
var vis = d3.select("#mydiv")
.append("svg");
var nodes = vis.selectAll("node")
.data(data, function(d) {return d.label})
var gs = nodes
.enter()
.append("g");
gs
.append("rect")
.attr("class", "node")
.attr("x", function(d) {return d.x})
// .attr("y", 80)
.attr("width", function(d) {return d.width})
.attr("height", 20)
.style("stroke", "#000000")
.style("fill", "#FF0000");
gs
.append("text")
.text(function(d) {return d.label})
.attr("x", function(d) {return d.x})
var force = d3.layout.force()
.nodes(data)
.size([800, 200])
.gravity(0.1)
.charge(-600);
nodes.call(force.drag);
force.on("tick", function(e) {
d3.selectAll("node.rect")
.each(function(d,i){d.y += (100-d.y) * e.alpha *.003});
vis.selectAll("rect")
.attr("y", function(d) { if (d.y < 10){ return 20} else {return d.y;} });
vis.selectAll("text")
.attr("y", function(d) { if (d.y < 10){ return 20} else {return d.y;} });
});
force.start();
function collide(node) {
var nx1 = node.x,
nx2 = node.x + node.width,
ny1 = node.y,
ny2 = node.y + node.width;
return function(quad, x1, y1, x2, y2) {
if (quad.point && (quad.point !== node)) {
var x = node.x - quad.point.x,
y = node.y - quad.point.y,
l = Math.sqrt(x * x + y * y),
r = node.radius + quad.point.radius;
if (l < r) {
l = (l - r) / l * .5;
node.x -= x *= l;
node.y -= y *= l;
quad.point.x += x;
quad.point.y += y;
}
}
return x1 > nx2
|| x2 < nx1
|| y1 > ny2
|| y2 < ny1;
};
}