Skip to content

Instantly share code, notes, and snippets.

@michiel
Last active December 11, 2019 09:28
Show Gist options
  • Save michiel/2e632cd50c435594cc44 to your computer and use it in GitHub Desktop.
Save michiel/2e632cd50c435594cc44 to your computer and use it in GitHub Desktop.
// based on http://onais-m.blogspot.nl/2014/10/automatic-graph-layout-with-javascript.html
var jsp = jsPlumb.getInstance();
// construct dagre graph from JsPlumb graph
/* global dagre */
var g = new dagre.graphlib.Graph();
g.setGraph({});
g.setDefaultEdgeLabel(function() { return {}; });
$('.xnode').each(
function(idx, node) {
var n = $(node);
g.setNode(n.attr('id'), {
width : Math.round(n.width()),
height : Math.round(n.height())
});
}
);
jsp.getAllConnections().forEach(
function(edge) {
g.setEdge(
edge.source.id,
edge.target.id
);
});
// calculate the layout (i.e. node positions)
dagre.layout(g);
// Applying the calculated layout
g.nodes().forEach(
function(n) {
$('#' + n).css('left', g.node(n).x + 'px');
$('#' + n).css('top', g.node(n).y + 'px');
});
jsp.repaintEverything();
@YuriGor
Copy link

YuriGor commented Jul 27, 2016

Thank you for usefull kick-starter.

I fixed some jQuery-related geometry issues, look at this fork:
https://gist.github.com/YuriGor/f464e73ae05572329bd188b6dd7fb6c3

dagre returns coordinates of the center of the node, not top left corner, so width and height of the node should be considered.
also jQuery width and height methods return content size of the element, without paddings and border.
So outerWidth and outerHeight methods should be used.

@YuriGor
Copy link

YuriGor commented Sep 3, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment