Files
tunmnlu/task_2/hw2_skeleton/Q2/Q2.html
louiscklaw 9035c1312b update,
2025-02-01 02:09:32 +08:00

162 lines
4.0 KiB
HTML

<!DOCTYPE html>
<html>
<head>
<style>
path.link {
fill: none;
stroke: #666;
stroke-width: 1.5px;
}
circle {
fill: #ccc;
stroke: #fff;
stroke: black;
stroke-width: 1.5px;
}
text {
fill: #000;
font: 10px sans-serif;
pointer-events: none;
}
</style>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<script type="text/javascript" src="../lib/d3.v5.min.js"></script>
<script>
d3.dsv(",", "board_games.csv", function (d) {
return {
source: d.source,
target: d.target,
value: +d.value,
};
})
.then(function (data) {
var links = data;
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 = 1200,
height = 700;
var force = d3
.forceSimulation()
.nodes(d3.values(nodes))
.force("link", d3.forceLink(links).distance(100))
.force("center", d3.forceCenter(width / 2, height / 2))
.force("x", d3.forceX())
.force("y", d3.forceY())
.force("charge", d3.forceManyBody().strength(-250))
.alphaTarget(1)
.on("tick", tick);
var svg = d3
.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);
// add the links
var path = svg
.append("g")
.selectAll("path")
.data(links)
.enter()
.append("path")
.attr("class", function (d) {
return "link " + d.type;
});
// define the nodes
var node = svg
.selectAll(".node")
.data(force.nodes())
.enter()
.append("g")
.attr("class", "node")
.call(
d3
.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended)
);
// add the nodes
node
.append("circle")
.attr("id", function (d) {
return d.name.replace(/\s+/g, "").toLowerCase();
})
.attr("r", 5);
// add the curvy lines
function tick() {
path.attr("d", function (d) {
var dx = d.target.x - d.source.x,
dy = d.target.y - d.source.y,
dr = Math.sqrt(dx * dx + dy * dy);
return (
"M" +
d.source.x +
"," +
d.source.y +
"A" +
dr +
"," +
dr +
" 0 0,1 " +
d.target.x +
"," +
d.target.y
);
});
node.attr("transform", function (d) {
return "translate(" + d.x + "," + d.y + ")";
});
}
function dragstarted(d) {
if (!d3.event.active) force.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) force.alphaTarget(0);
if (d.fixed == true) {
d.fx = d.x;
d.fy = d.y;
} else {
d.fx = null;
d.fy = null;
}
}
})
.catch(function (error) {
console.log(error);
});
</script>
</body>
</html>