Springy.js

A force directed graph layout algorithm in JavaScript.

Chamaecyparis obtusa

Demo | Download | Usage | GitHub | Contact

What is Springy?

Springy is a force directed graph layout algorithm.

So what does this “force directed” stuff mean anyway? Excellent question!

It means that springy uses some real world physics to try and figure out how to show a network graph in a way that looks good.

Here's an example:

Sequoya gigantea

Usage

Here's how you create a graph and add nodes and edges:

// make a new graph
var graph = new Graph();

// make some nodes
var spruce = graph.newNode({label: 'Norway Spruce'});
var fir = graph.newNode({label: 'Sicilian Fir'});

// connect them with an edge
graph.newEdge(spruce, fir);

Once you've created your graph, there are a couple of options for displaying it.

To help get started quickly, I've included a helper jQuery plugin included called springyui.js. It's got a semi‑decent default renderer and some half‑assed drag and drop.

Here's how to use springyui.js:

<canvas id="my_canvas" width="600" height="400" />
<script>
$('#my_canvas').springy({ graph: graph });
</script>

Advanced usage

If you're keen to do your own custom drawing or interaction—there's a few extra things you'll need to know.

The core Springy layout algorithm is in the Layout.ForceDirected class.

When creating a layout object, there are a few parameters you can tune to make the graph layout algorithm behave how you like:

var layout = new Layout.ForceDirected(
  graph,
  400.0, // Spring stiffness
  400.0, // Node repulsion
  0.5 // Damping
);

To simplify the layout calculation and animation rendering loop, I've provided a Renderer class. You just need to provide some callbacks to do the actual drawing:

var renderer = new Renderer(
  layout,
  function clear() {
    // code to clear screen
  },
  function drawEdge(edge, p1, p2) {
    // draw an edge
  },
  function drawNode(node, p) {
    // draw a node
  }
);

Then to start the rendering loop:

renderer.start();

Protip: Take a look at the source code of springyui.js to get an idea of how to write your own renderer—it's a good place to start. Feel free to copy‑paste what you need.

Pinus serotina

Further reading

Take a look at the source code of springy.js. Don't be shy—there's not that much code and it should be pretty easy to understand.

Please let me know if anything is unclear. Feedback is welcome. :-)

Cupressus sempervirens

License

Springy is licensed under the MIT license.

Acknowledgements

Thanks to Lachlan Donald for his helpful suggestions and feedback.

Thanks to Ernst Haeckel for the beautiful illustrations of Coniferae.

Araucaria brasiliana