greuler是图形理论可视化工具,基于D3和WebCola。greuler允许使用一个简单的API创建和操作图形。
使用引入资源:
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.js"></script> <script src="https://marvl.infotech.monash.edu/webcola/cola.v3.min.js"></script>安装:
bower install greuler插入到项目中:
<script src="bower_components/greuler/dist/greuler.js"></script>简单示例欧拉轨迹
'use strict';window.d3.json('scripts/examples/data/eulerian-graph.json', function (error, data) { var instance = greuler({ target: '#eulerian-trail', width: 600, height: 600, animationTime: 500, data: data }).update(); window.examples['eulerian-trail'] = function () { var greuler = window.greuler; var player = new greuler.player.Generator(instance); player.run(function *algorithm(instance) { var stack = []; var trail = []; function eulerianTrail(u) { stack.push(u); var edges = instance.graph.getIncidentEdges({ id: u }); for (var i = 0; i < edges.length; i += 1) { var e = edges[i]; var next = e.target.id === u ? e.source.id : e.target.id; if (e.used) { continue; } e.used = true; eulerianTrail(next); } trail.push(stack.pop()); } eulerianTrail(0); // node traversal is given by trail for (var i = 0; i < trail.length; i += 1) { yield function () { instance.selector.traverseAllEdgesBetween( { source: trail[i], target: trail[i + 1] } ); }; } }); };});广度优先搜索:
'use strict';(function () { var greuler = window.greuler; var instance = greuler({ target: '#bfs', width: 600, height: 600, animationTime: 500, data: greuler.Graph.random({ connected: true }) }).update(); window.examples.bfs = function () { var player = new greuler.player.Generator(instance); player.run(function *algorithm(instance) { function *bfs(source) { // queue var distance = []; var q = []; var parent = []; function highlight(id, visit) { return function () { var node = instance.graph.getNode({ id: id }); node.topRightLabel = distance[id]; instance.selector.highlightNode({ id: id }); if (visit) { instance.selector.getNode({ id: id }) .transition() .attr('fill', 'black'); } instance.update({skipLayout: true}); }; } distance[source] = 0; q.push(source); while (q.length) { var top = q.shift(); var adjacent = instance.graph.getAdjacentNodes({ id: top }); yield highlight(top, true); for (var i = 0; i < adjacent.length; i += 1) { var next = adjacent[i].id; if (next === parent[top]) { continue; } if (typeof distance[next] === 'undefined') { distance[next] = distance[top] + 1; parent[next] = top; q.push(next); yield function () { instance.selector.traverseAllEdgesBetween( { source: top, target: next } ); }; yield highlight(next); } else { yield function () { instance.selector.traverseAllEdgesBetween( { source: top, target: next }, { keepStroke: false } ) .transition() .attr('opacity', 0.3); }; } } } } yield *bfs(0); }); };})();
评论