-
Notifications
You must be signed in to change notification settings - Fork 0
/
skillsNetworkGraph.html
109 lines (92 loc) · 3.53 KB
/
skillsNetworkGraph.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
<!DOCTYPE html>
<html>
<head>
<title>Force Directed Graph</title>
<script src="https://d3js.org/d3.v4.min.js"></script>
<link href="https://fonts.googleapis.com/css2?family=Comic+Neue:wght@700&display=swap" rel="stylesheet">
<style>
.links line {
stroke: #424a4d;
}
.nodes text {
pointer-events: none;
font: 17px 'Comic Neue', sans-serif;
font-weight: bold;
}
</style>
</head>
<body>
<script>
var svg = d3.select("body").append("svg")
.attr("width", window.innerWidth)
.attr("height", window.innerHeight);
var simulation = d3.forceSimulation()
.force("link", d3.forceLink().distance(200).id(function(d) { return d.id; }))
.force("charge", d3.forceManyBody().strength(-500))
.force("center", d3.forceCenter(window.innerWidth / 2, window.innerHeight / 2));
d3.json("skills.json", function(error, graph) {
if (error) throw error;
var link = svg.append("g")
.attr("class", "links")
.selectAll("line")
.data(graph.links)
.enter().append("line");
var node = svg.append("g")
.attr("class", "nodes")
.selectAll("g")
.data(graph.nodes)
.enter().append("g");
var circles = node.append("circle")
.attr("r", function(d) { return d.size; })
.attr("fill", function(d) { return d.color; })
.on("click", function(d) {
console.log("Clicked on node: ", d.id, d.url); // 输出点击的节点的id
if (d.url) {
console.log("Opening URL: ", d.url); // 输出即将打开的URL
window.location.href = d.url; // 在当前窗口打开链接
}
})
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));
var labels = node.append("text")
.text(function(d) { return d.id; })
.attr('x', function(d) { return d.size + 2; }) // place text to right of node
.attr('y', 3);
node.append("title")
.text(function(d) { return d.id; });
simulation
.nodes(graph.nodes)
.on("tick", ticked);
simulation.force("link")
.links(graph.links);
function ticked() {
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; });
node
.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
})
}
});
function dragstarted(d) {
if (!d3.event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}
function dragged(d) {
d.fx = d3.event.x;
d.fy = d3.event.y;
}
function dragended(d) {
if (!d3.event.active) simulation.alphaTarget(0).restart();
d.fx = null;
d.fy = null;
}
</script>
</body>
</html>