A positioning force that help to keep nodes visible on the screen.
Built with blockbuilder.org
forked from john-guerra's block: d3.forceBoundary Forces no Border
forked from john-guerra's block: d3.forceBoundary Forces with Border
xxxxxxxxxx
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<canvas width=960 height=460></canvas>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script type="text/javascript" src="https://unpkg.com/d3-force-boundary/dist/d3-force-boundary.js"></script>
<script>
/* global d3, forceBoundary */
var canvas = d3.select("canvas").node(),
ctx= canvas.getContext("2d"),
width = canvas.width,
height = canvas.height,
r=2;
d3.json("https://gist.githubusercontent.com/john-guerra/ef11d9fcf36e4d6a35be583aa69ac95b/raw/0fbedcebdaa1854cc1b89d86e2d8174520f6ec2d/coauthorshipNetwork2015.json", function (err, graph) {
if (err) throw err;
const simulation = d3.forceSimulation(graph.nodes)
.force("boundary",
forceBoundary(0, 0, width -r, height-r )
.strength(0.1)
// .border(100)
.hardBoundary(true))
// .force("x", d3.forceX(width/2).strength(0.1))
// .force("y", d3.forceY(height/2).strength(0.1))
.force("charge", d3.forceManyBody().strength(-10))
.force("link", d3.forceLink(graph.links).distance(10))
.on("tick", ticked);
function ticked() {
ctx.clearRect(0, 0, width, height);
ctx.save();
ctx.strokeStyle="rgba(100,100,100,0.3)";
ctx.beginPath();
for (let l of graph.links) {
ctx.moveTo(l.source.x, l.source.y);
ctx.lineTo(l.target.x, l.target.y);
}
ctx.stroke();
ctx.fillStyle="steelblue";
ctx.beginPath();
for (let n of graph.nodes) {
ctx.moveTo(n.x, n.y);
ctx.arc(n.x+r/2, n.y+r/2, r, 0, 2 * Math.PI);
}
ctx.fill();
ctx.restore();
} // ticked
});
</script>
</body>
</html>
Modified http://d3js.org/d3.v4.min.js to a secure url
https://d3js.org/d3.v4.min.js
https://unpkg.com/d3-force-boundary/dist/d3-force-boundary.js