Built with blockbuilder.org
xxxxxxxxxx
<meta charset="utf-8">
<style>
.link {
stroke: black;
}
.node {
stroke: black;
}
.label {
font-size: 12px;
color: white;
}
</style>
<svg width="1000" height="500"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height");
var color = d3.scaleOrdinal(d3.schemeCategory20);
var xScale = d3.scaleLinear().domain([0, 1]).range([0, 600]);
var simulation = d3.forceSimulation()
.force("link", d3.forceLink().distance(70).id(function(d) { return d.id; }))
.force("charge", d3.forceManyBody())
.force('y', d3.forceY().y(function(d) {
if ('QWERTYUIOP'.includes(d.id)) {
return 0;
} else if ('ASDFGHJKL'.includes(d.id)) {
return 300;
} else {
return 400;
}
}))
.force("center", d3.forceCenter(width / 2, height / 2));
d3.select("circle")
d3.json("data.json", function(error, graph) {
if (error) throw error;
var link = svg.append("g")
.attr("class", "link")
.selectAll("line")
.data(graph.links)
.enter().append("line")
var nodeData = svg.append("g")
.selectAll("circle")
.attr("class", "node")
.data(graph.nodes).enter();
var node = nodeData.append("circle")
.attr("r", 15)
.attr("id", function(d) {return 'node'+d.id})
.attr('fixed', true)
.attr("py", function(d) {
})
.attr("fill", function(d) { return color(d.group); })
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));
var label = svg.selectAll()
.data(graph.nodes).enter()
.append("text")
.attr("class", "label")
.text(function (d) { return d.id; })
.style("text-anchor", "middle")
.style("fill", "white")
.style("font-family", "Arial")
.style("font-size", 12)
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));
d3.select("body").on("keydown", keyPress)
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("cx", function(d) { return d.x;})
.attr("cy", function(d) { return d.y; });
label
.attr("x", function(d) { return d.x;})
.attr("y", function(d) { return d.y; });
}
});
function keyPress() {
var key = d3.event && d3.event.key && d3.event.key.toUpperCase();
if (key) {
var node = d3.select('#node' + key);
if (node) {
console.log(node);
var oldr = parseInt(node.attr("r"));
d3.select('#node' + key).attr("r",oldr+1);
}
}
}
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>
https://d3js.org/d3.v4.min.js