Skip to content

Instantly share code, notes, and snippets.

@rfilmyer
Last active July 26, 2016 22:44
Show Gist options
  • Save rfilmyer/a4defbec68247c019bb1e73c67610e21 to your computer and use it in GitHub Desktop.
Save rfilmyer/a4defbec68247c019bb1e73c67610e21 to your computer and use it in GitHub Desktop.
D3 V4.0 Force Graph (using Canvas)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<canvas height="100%" width="100%"></canvas>
<script src="//d3js.org/d3.v4.min.js"></script>
<script>
var canvas = document.querySelector("canvas");
canvas.width = (window.innerWidth*4) || 960; // tuned for large force diagrams
canvas.height = (window.innerHeight*4) || 500;
var context = canvas.getContext("2d"),
width = canvas.width,
height = canvas.height;
var simulation = d3.forceSimulation()
.force("link", d3.forceLink()
.id(function(d) { return d.id; })
//.distance(function(d) {return 30*d.value/250})
)
.force("charge", d3.forceManyBody()
.strength(-20)
.distanceMin(0)
.distanceMax(2000))
.force("center", d3.forceCenter(width / 2, height / 2))
.force("force-x", d3.forceX()
.strength(0.1))
.force("force-y", d3.forceY()
.strength(0.1));
d3.json("nodes.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.moveTo(d.x + 3, d.y);
context.arc(d.x, d.y, 3, 0, 2 * Math.PI);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment