D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
esjewett
Full window
Github gist
d3-force collide fix
Built with
blockbuilder.org
forked from
esjewett
's block:
fresh block
<!DOCTYPE html> <head> <meta charset="utf-8"> <style> body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; } line { stroke: #ccc; } circle { stroke: none; stroke-width: 40px; } .nodes1 { fill: grey; } .nodes2 { fill: blue } </style> <script src="d3.js"></script> </head> <body> <svg height="200px" width="200px"></svg> <script> var nodes1 = [{a: "a"}, {a: "b"}, {a: "c"}] var nodes2 = [{a: "d"}, {a: "e"}, {a: "f"}] var links = [{ source: nodes1[0], target: nodes1[1] }, { source: nodes1[2], target: nodes2[2] }, { source: nodes1[0], target: nodes2[1] }] var s = d3.select('svg') var tick1 = function() { s .selectAll('circle.nodes1') .data(simulation1.nodes()) .attr('transform', function(d) { return 'translate(' + d.x + ',' + d.y + ')'; }) } var tick2 = function() { s .selectAll('circle.nodes2') .data(simulation2.nodes()) .attr('transform', function(d) { return 'translate(' + d.x + ',' + d.y + ')'; }) } var simulation1 = d3.forceSimulation(nodes1); var simulation2 = d3.forceSimulation(nodes2); var simulation3 = d3.forceSimulation(nodes1.concat(nodes2)); simulation1 .force('collision', d3.forceCollide().radius(40)) simulation2 .force('collision', d3.forceCollide().radius(40)) simulation3 .force('link', d3.forceLink(links)) .force("center", d3.forceCenter(100, 100)) .force('xposition', d3.forceX(100).strength(0.1)) .force('yposition', d3.forceY(100).strength(0.1)) s .selectAll('circle.nodes1') .data(simulation1.nodes()) .enter() .append('circle') .attr('class', 'nodes1') .attr('r', 10) s .selectAll('circle.nodes2') .data(simulation2.nodes()) .enter() .append('circle') .attr('class', 'nodes2') .attr('r', 10) s.selectAll('line') .data(links) .enter() .append('line') simulation1.on('tick', tick1) simulation2.on('tick', tick2) simulation3.on('tick', function() { s.selectAll('line') .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; }); }) </script> </body>