-
Notifications
You must be signed in to change notification settings - Fork 246
/
index.html
76 lines (68 loc) · 2.57 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<head>
<style> body { margin: 0; } </style>
<script src="//unpkg.com/force-graph"></script>
<!--<script src="../../dist/force-graph.js"></script>-->
</head>
<body>
<div id="graph"></div>
<script>
const gData = {
nodes: [{ id: 0 }, { id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }],
links: [
{ source: 0, target: 1 },
{ source: 0, target: 1 },
{ source: 1, target: 0 },
{ source: 1, target: 2 },
{ source: 2, target: 2 },
{ source: 2, target: 2 },
{ source: 2, target: 2 },
{ source: 2, target: 3 },
{ source: 3, target: 4 },
{ source: 4, target: 3 }
]
};
let selfLoopLinks = {};
let sameNodesLinks = {};
const curvatureMinMax = 0.5;
// 1. assign each link a nodePairId that combines their source and target independent of the links direction
// 2. group links together that share the same two nodes or are self-loops
gData.links.forEach(link => {
link.nodePairId = link.source <= link.target ? (link.source + "_" + link.target) : (link.target + "_" + link.source);
let map = link.source === link.target ? selfLoopLinks : sameNodesLinks;
if (!map[link.nodePairId]) {
map[link.nodePairId] = [];
}
map[link.nodePairId].push(link);
});
// Compute the curvature for self-loop links to avoid overlaps
Object.keys(selfLoopLinks).forEach(id => {
let links = selfLoopLinks[id];
let lastIndex = links.length - 1;
links[lastIndex].curvature = 1;
let delta = (1 - curvatureMinMax) / lastIndex;
for (let i = 0; i < lastIndex; i++) {
links[i].curvature = curvatureMinMax + i * delta;
}
});
// Compute the curvature for links sharing the same two nodes to avoid overlaps
Object.keys(sameNodesLinks).filter(nodePairId => sameNodesLinks[nodePairId].length > 1).forEach(nodePairId => {
let links = sameNodesLinks[nodePairId];
let lastIndex = links.length - 1;
let lastLink = links[lastIndex];
lastLink.curvature = curvatureMinMax;
let delta = 2 * curvatureMinMax / lastIndex;
for (let i = 0; i < lastIndex; i++) {
links[i].curvature = - curvatureMinMax + i * delta;
if (lastLink.source !== links[i].source) {
links[i].curvature *= -1; // flip it around, otherwise they overlap
}
}
});
const Graph = ForceGraph()
(document.getElementById('graph'))
.linkCurvature('curvature')
.linkDirectionalArrowLength(6)
.linkDirectionalArrowRelPos(1)
.graphData(gData);
</script>
</body>