Incremental expand
Open in a new window.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="../build/ogma.min.js"></script>
<style>
#graph-container {
top: 0;
bottom: 0;
left: 0;
right: 0;
position: absolute;
margin: 0;
overflow: hidden;
}
#add {
position: absolute;
top: 20px;
right: 20px;
}
</style>
</head>
<body>
<div id="graph-container"></div>
<script>
'use strict';
var ogma = new Ogma({
container: 'graph-container'
});
var duration = 500;
// Generates graph with high-degree nodes
function generateDenseTree(startNodeId, startEdgeId, N, maxR, minR) {
maxR = maxR || 10;
minR = minR || 5;
return new Promise(function (resolve, reject) {
var nodes = new Array(N).fill(0).map(function (_, i) {
return {
id: startNodeId + i,
attributes: {
text: 'Node #' + i,
radius: minR + Math.random() * (maxR - minR),
x: -50 + Math.random() * 100,
y: -50 + Math.random() * 100
}
};
});
var edges = new Array(N - 1).fill(0).map(function (_, i) {
return {
id: startEdgeId + i,
source: startNodeId + Math.floor(Math.sqrt(i) / 2),
target: startNodeId + i + 1
};
});
resolve({ nodes: nodes, edges: edges });
});
}
function expand() {
var nodes = ogma.getNodes();
var root = nodes.get(Math.floor(nodes.size * Math.random()));
var rootPos = root.getPosition();
generateDenseTree(ogma.getNodes().size, ogma.getEdges().size, 20)
.then(function (g) {
g.edges.push({ source: root.getId(), target: g.nodes[0].id });
return ogma.addGraph(g);
})
.then(function (g) { return g.nodes.setAttributes(rootPos); })
.then(function (nodes) {
return ogma.layouts.force({
incremental: true,
nodes: nodes,
randomize: 'locally', // to deal with node overlapping
duration: duration || 0,
locate: true
});
});
}
// generate graph and collapse the nodes
generateDenseTree(0, 0, 20)
.then(function (graph) { return ogma.setGraph(graph); })
.then(function () { return ogma.layouts.forceLink(); })
.then(ogma.view.locateGraph);
</script>
<button id="add" onclick="expand()">Add nodes</button>
</body>
</html>