Created
January 21, 2020 18:45
-
-
Save nautilytics/9b2ee31d829516efe59fc56794a196c7 to your computer and use it in GitHub Desktop.
Using d3-force simulation to place points
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const calculateLayout = (items, spacing = 0.01) => { | |
// Calculate a force directed placement for each point | |
const MAX_STEPS = 300, | |
STRENGTH = 10, | |
ALPHA = 0.3; | |
if (!items.length) return []; | |
const getY = d => d.y; | |
const getX = d => d.x; | |
const getCollision = d => d.r + spacing; | |
const sim = forceSimulation(items) | |
.force('collide', forceCollide(getCollision)) | |
.force('x', forceX(getX).strength(STRENGTH)) | |
.force('y', forceY(getY).strength(STRENGTH)) | |
.alpha(ALPHA) | |
.stop(); | |
const upperBound = Math.ceil(Math.log(sim.alphaMin()) / Math.log(1 - sim.alphaDecay())); | |
for (let i = 0; i < Math.min(MAX_STEPS, upperBound); ++i) sim.tick(); | |
return items; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment