JSFiddle - React, Tailwind, and code Playground
CSS
.link-line {
fill: none;
stroke: #666;
stroke-width: 1.5px;
}
.node circle {
fill: #ccc;
stroke: #fff;
stroke-width: 1.5px;
}
text {
font: 10px sans-serif;
pointer-events: none;
}
JavaScript
// http://blog.thomsonreuters.com/index.php/mobile-patent-suits-graphic-of-the-day/
var links = [{
source: "A",
target: "B",
type: "price",
size: '<'
}];
var nodes = {};
// Compute the distinct nodes from the links.
links.forEach(function(link) {
link.source = nodes[link.source] || (nodes[link.source] = {
name: link.source
});
link.target = nodes[link.target] || (nodes[link.target] = {
name: link.target
});
});
var width = 960,
height = 500;
var force = d3.layout.force()
.nodes(d3.values(nodes))
.links(links)
.size([width, height])
.linkDistance(150)
.charge(-300)
.on("tick", tick)
.start();
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var link = svg.selectAll(".link")
.data(force.links())
.enter()
.append("g")
.attr("class", "link")
.append("line")
.attr("class", "link-line");
var node = svg.selectAll(".node")
.data(force.nodes())
.enter().append("g")
.attr("class", "node")
.on("mouseover", mouseover)
.on("mouseout", mouseout)
.call(force.drag);
node.append("circle")
.attr("r", 8);
node.append("text")
.attr("dx", 12)
.attr("dy", ".35em")
.text(function(d) {
return d.name;
});
var labelLine = svg.selectAll(".link")
.append("text")
.attr("class", "link-label")
.attr("font-family", "Arial, Helvetica, sans-serif")
.attr("fill", "Black")
.style("font", "bold 18px Arial")
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.text(function(d) {
return d['size'];
});
function tick() {
link
.attr("x1", function(d) {
return d.source.x;
})
.attr("y1", function(d) {
return d.source.y;
})
.attr("x2", function(d) {
return d.target.x;
})
.attr("y2", function(d) {
return d.target.y;
});
labelLine.attr("transform", function(d) {
if (d) {
const dsty = d.source.y - d.target.y;
let angle = Math.atan(dsty / (d.source.x - d.target.x)) * 180 / Math.PI;
...