D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
madams1
Full window
Github gist
d3 force directed particle flow (v4)
<!DOCTYPE html> <meta charset="utf-8"> <body> <button id="combine-btn" style="margin-left:10px; margin-top:10px;">Combine</button> <button id="separate-btn" style="margin-left:3px; margin-top:10px;">Separate</button> <button id="restart-btn" style="margin-left:700px; margin-top:10px;">Restart</button> <div id="target"></div> <script src="//d3js.org/d3.v4.min.js"></script> <script src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script> <script> const width = 960, height = 600, radius = 4, color = d3.schemePaired; let nodes = [], counter = 0, int; let svg = d3.select("#target").append("svg") .attr("width", width) .attr("height", height); let simulation = d3.forceSimulation() .force("x", d3.forceX().x(width/2)) .force("y", d3.forceY().y(height/2)) .force("gravity", d3.forceManyBody().strength(-radius)) .force("collide", d3.forceCollide() .radius(d => d.radius + 1.1) .iterations(5) ) .on("tick", () => { svg.selectAll("circle") .attr("cx", d => d.x) .attr("cy", d => d.y); }); startSimulation(); function startSimulation() { int = d3.interval(() => { addNode(); updateSim(); if (counter > 440) { int.stop(); } }, 80); } function addNode() { let offenseGroup = Math.floor(d3.randomUniform(7)()) + 1; nodes.push( { radius, x: width/2, y: 0, offenseGroup, fill: color[offenseGroup] } ); counter += 1; } d3.select("#combine-btn").on("click", () => combine()); d3.select("#separate-btn").on("click", () => separate()); d3.select("#restart-btn").on("click", () => restart()); function restart() { nodes = []; counter = 0; int.stop(); simulation.restart(); updateSim(); startSimulation(); } function separate() { simulation.force("x", d3.forceX().x(d => d.offenseGroup * width/8)); } function combine() { simulation.force("x", d3.forceX().x(width/2)); } function updateSim() { simulation.nodes(nodes); let bubs = svg.selectAll("circle") .data(nodes); bubs.exit().remove(); bubs.enter().append("circle") .attr("r", function(d) { return d.radius; }) .attr("cx", d => d.x) .attr("cy", d => d.y) .attr("stroke", d => d3.rgb(d.fill).darker()) .attr("stroke-width", 1) .style("fill", function(d) { return d.fill; }) .style("opacity", 0.6) .merge(bubs); simulation.alphaTarget(0.5); } </script>
https://d3js.org/d3.v4.min.js
https://d3js.org/d3-scale-chromatic.v1.min.js