Built with blockbuilder.org. Modified Force Dragging III with node colors, node labels, label colors and sizes.
forked from shashank2104's block: fresh block
xxxxxxxxxx
<meta charset="utf-8">
<canvas width="960" height="600"></canvas>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var canvas = document.querySelector("canvas"),
context = canvas.getContext("2d"),
width = canvas.width,
height = canvas.height;
var simulation = d3.forceSimulation()
.force("link", d3.forceLink().id(function(d) { return d.id; }))
.force("charge", d3.forceManyBody())
.force("center", d3.forceCenter(width / 2, height / 2));
var nodeColors = d3.scaleOrdinal().range(d3.schemeCategory20),
labelColors = d3.scaleOrdinal().range(['red', 'orange', 'blue', 'yellow', 'purple']);
d3.json("miserables.json", function(error, graph) {
if (error) throw error;
simulation
.nodes(graph.nodes)
.on("tick", ticked);
simulation.force("link")
.links(graph.links);
d3.select(canvas)
.call(d3.drag()
.container(canvas)
.subject(dragsubject)
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));
function ticked() {
context.clearRect(0, 0, width, height);
context.beginPath();
graph.links.forEach(drawLink);
context.strokeStyle = "#aaa";
context.stroke();
context.beginPath();
graph.nodes.forEach(drawNode);
context.fill();
context.strokeStyle = "#fff";
context.stroke();
}
function dragsubject() {
return simulation.find(d3.event.x, d3.event.y);
}
});
function dragstarted() {
if (!d3.event.active) simulation.alphaTarget(0.3).restart();
d3.event.subject.fx = d3.event.subject.x;
d3.event.subject.fy = d3.event.subject.y;
}
function dragged() {
d3.event.subject.fx = d3.event.x;
d3.event.subject.fy = d3.event.y;
}
function dragended() {
if (!d3.event.active) simulation.alphaTarget(0);
d3.event.subject.fx = null;
d3.event.subject.fy = null;
}
function drawLink(d) {
context.moveTo(d.source.x, d.source.y);
context.lineTo(d.target.x, d.target.y);
}
function drawNode(d) {
context.beginPath();
context.moveTo(d.x+10, d.y);
context.arc(d.x, d.y, 10, 0, 2 * Math.PI);
context.strokeStyle = "#fff";
context.stroke();
context.fillStyle = nodeColors(d.group);
context.closePath();
context.fill();
context.beginPath();
context.font = (d.labelSize ? d.labelSize : 13)+'px Arial';
context.fillStyle = labelColors(d.group);
context.fillText(d.label ? d.label : d.group, d.x,d.y);
context.closePath();
}
</script>
https://d3js.org/d3.v4.min.js