JSFiddle - React, Tailwind, and code Playground
by nija das
HTML
<script src="http://d3js.org/d3.v3.min.js"></script>
CSS
.link {
stroke: #000;
}
JavaScript
var graph = {
"nodes": [{
"name": "Node 1",
"group": 1
}, {
"name": "Node 2",
"group": 1
}, {
"name": "Node 3",
"group": 1
}, {
"name": "Node 4",
"group": 2
}, {
"name": "Node 5",
"group": 2
}],
"links": [{
"source": 1,
"target": 0,
"value": 1
}, {
"source": 2,
"target": 1,
"value": 2
}, {
"source": 3,
"target": 2,
"value": 3
}, {
"source": 4,
"target": 3,
"value": 1
}, {
"source": 0,
"target": 4,
"value": 2
}, {
"source": 3,
"target": 1,
"value": 1
}, ]
};
var width = 300,
height = 200;
var color = d3.scale.category20();
var force = d3.layout.force()
.charge(-220)
.linkDistance(75)
.size([width, height]);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
force.nodes(graph.nodes)
.links(graph.links)
.start();
var nodeRadius = 10;
var lineX2 = function (d) {
var length = Math.sqrt(Math.pow(d.target.y - d.source.y, 2) + Math.pow(d.target.x - d.source.x, 2));
var scale = (length - nodeRadius) / length;
var offset = (d.target.x - d.source.x) - (d.target.x - d.source.x) * scale;
return d.target.x - offset;
};
var lineY2 = function (d) {
var length = Math.sqrt(Math.pow(d.target.y - d.source.y, 2) + Math.pow(d.target.x - d.source.x, 2));
var scale = (length - nodeRadius) / length;
var offset = (d.target.y - d.source.y) - (d.target.y - d.source.y) * scale;
return d.target.y - offset;
};
var link = svg.selectAll("line.link")
.data(graph.links)
.enter().append("svg:line")
.attr("class", "link")
.style("stroke-width", function (d) {
return Math.sqrt(d.value);
})
.attr("x1", function (d) {
return...