Skip to content

Instantly share code, notes, and snippets.

@jwilber
Last active January 31, 2019 05:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jwilber/bd6d2a499146daf05ccf7bb19a6aa0bf to your computer and use it in GitHub Desktop.
Save jwilber/bd6d2a499146daf05ccf7bb19a6aa0bf to your computer and use it in GitHub Desktop.
apply force to existing nodes
license: mit
<!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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment