xxxxxxxxxx
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
body {
margin: 5;
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
.links line {
stroke: #999;
stroke-opacity: 0.6;
}
.nodes circle {
stroke: #fff;
stroke-width: 1.5px;
}
.node text {
font: 10px sans-serif;
}
</style>
</head>
<body>
<script>
// Feel free to change or delete any of the code you see in this editor!
var width = 500
var height = 500
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.style("border", "1px solid black")
var node, link
var color = d3.scaleOrdinal(d3.schemeCategory20);
var simulation = d3.forceSimulation()
.force("link", d3.forceLink().id((d) => d.id).distance(() => 200))
.force("charge", d3.forceManyBody())
.force("center", d3.forceCenter(width / 2, height / 2));
function once() {
svg.append("g").attr("class", "links")
svg.append("g").attr("class", "nodes")
}
once()
function handleGraph(error, graph) {
if (error) throw error;
console.log("Handling graph")
link = svg.select("g.links")
.selectAll("line")
.data(graph.links, (d) => d.id)
var enterLink = link.enter().append("line")
.attr("stroke-width", function(d) {
return Math.sqrt(d.value);
});
link = enterLink.merge(link)
node = svg.select("g.nodes")
.selectAll(".node")
var enterNode = node.data(graph.nodes, (d) => d.id)
.enter().append("g")
.attr("class", "node")
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));
node = enterNode.merge(node)
var circle = node.append("circle")
.attr("r", 5)
.attr("fill", function(d) {
return color(d.group);
})
var text = node.append("text")
.attr("dx", 12)
.attr("dy", ".35em")
.text((d) => d.title);
var oldNodes = simulation.nodes()
console.log(oldNodes)
// if (oldNodes.length !== 0) {
// graph.nodes = oldNodes
// }
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 + ")";
});
}
}
d3.json("abra.json", handleGraph);
window.setTimeout(() => d3.json("abra.json", handleGraph), 3000)
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);
d.fx = null;
d.fy = null;
}
</script>
</body>
https://d3js.org/d3.v4.min.js