D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
jwilber
Full window
Github gist
apply force to existing nodes
Built with
blockbuilder.org
<!DOCTYPE html> <head> <meta charset="utf-8"> <script src="https://d3js.org/d3.v4.min.js"></script> <style> body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; } </style> </head> <body> <button id='applyForce' type='button'>Apply Force</button> </svg> <script> const width = 1000 const height = 600 const svg = d3.select("body").append("svg") .attr("width", width) .attr("height", height) let sampleData = d3.range(200).map(d => ({r: 5})); svg.selectAll('circle') .data(sampleData) .enter() .append('circle') .attr('r', d => d.r) .attr('fill', 'pink') .attr('cx', (d,i) => 50 + (i % 60)*12) .attr('cy', (d,i) => height / (2 + Math.floor(i/60)/10)); function applyForce() { const roleScale = d3.scaleOrdinal() .range(['coral', 'olive', 'skyblue', 'pink']); // set params for force layout const manyBody = d3.forceManyBody().strength(1) const center = d3.forceCenter().x((width/2)).y((height/2)) // define force let force = d3.forceSimulation() .force('charge', manyBody) .force('center', center) .force('collision', d3.forceCollide(d => d.r + 0)) .nodes(sampleData) .on('end', moveNodes); function moveNodes() { d3.selectAll('circle') .transition() .duration(1000) .attr('cx', d => d.x) .attr('cy', d => d.y) } }; //applyForce d3.select('#applyForce') .on('click', () => { console.log('clicked') applyForce() }); </script> </body>
https://d3js.org/d3.v4.min.js