Implement gravitational attraction (or force-field-like repulsion) using d3-force
Go here for a live demo and here for the code used in the demo
Using npm :
$ npm install --save d3-force-gravity
If you want to use this directly on your browser, use the contents of d3-force-gravity.min.js
, or, include this script after the d3 library in your HTML file :
<script src="https://raw.githubusercontent.com/sohamkamani/d3-force-gravity/master/d3-force-gravity.min.js" charset="utf-8"></script>
Check out the d3-force docs for a general overview on how d3-force works.
Using npm :
const width = 200
const height = 400
//First, require the module
const forceGravity = require('d3-force-gravity')
//Add it to your d3 force simulation, just like other forces
d3.forceSimulation()
.force('gravity', forceGravity(width/2, height/2))
Using directly in the browser :
- Follow installation steps above, and include the appropriate script.
- This force will be made available on
d3.forceGravity
. - Be sure to include the d3 library first
Creates a new gravitational force centered on the coordinates x
and y
.
Defaults :
x : 0
y : 0
Returns a new gravity
force
If strength
is specified, sets the strength of the force to its value, and returns the force.
If it is not specified, returns the current value of the forces strength.
If the strength is negative, it will lead to replusion of all nodes from the center of the force.
Default : 10000
The minimum radius outside of which this force is applied. Any node closer in distance to the center than this value, is not affected by the force. This is to prevent the enormous amount of force that would result from particles getting too close (tending to infinity at the center)
If minRadius
is specified, sets the minRadius of the force to its value, and returns the force.
If it is not specified, returns the current value of the forces minRadius.
Default : 40
Set the x coordinate of the center of the force.
If x
is specified, sets the x coordinate of the force to its value, and returns the force.
If it is not specified, returns the current value of the forces x coordinate.
Set the y coordinate of the center of the force.
If y
is specified, sets the y coordinate of the force to its value, and returns the force.
If it is not specified, returns the current value of the forces y coordinate.
MIT © sohamkamani