// 初始化gojs布局相关 function ContinuousForceDirectedLayout() { go.ForceDirectedLayout.call(this); this._isObserving = false; } go.Diagram.inherit(ContinuousForceDirectedLayout, go.ForceDirectedLayout); // 初始化gojs function initGraph() { var $ = go.GraphObject.make; myDiagram = $(go.Diagram, 'myDiagramDiv', { 'toolManager.mouseWheelBehavior': go.ToolManager.WheelZoom, initialContentAlignment: go.Spot.Center, hasHorizontalScrollbar: false, hasVerticalScrollbar: false, 'undoManager.isEnabled': true, 'draggingTool.isGridSnapEnabled': true, layout: $(ContinuousForceDirectedLayout, { arrangesToOrigin: true, defaultSpringLength: 30, defaultElectricalCharge: 100 }), SelectionMoved: function (e) { e.diagram.layout.invalidateLayout(); } });在这段代码基础上增加水平引力,让让元素横向排布
时间: 2024-01-03 13:03:41 浏览: 154
可以在 ContinuousForceDirectedLayout 的构造函数中添加一个新的属性 horizontalGravity,表示元素之间的横向引力:
```
function ContinuousForceDirectedLayout() {
go.ForceDirectedLayout.call(this);
this._isObserving = false;
this.horizontalGravity = 0.5;
}
```
然后在计算布局时,将横向引力添加到计算过程中:
```
ContinuousForceDirectedLayout.prototype.doLayout = function(coll) {
var diagram = this.diagram;
if (diagram === null) return;
if (coll === null) coll = this.collectParts();
var root = this.findRoots();
var v = this.createVertexes(coll);
var e = this.createEdges(coll);
this.initValues(v, e, root);
this.computeEffectiveLengths(v, e);
this.iterateLayout(v, e);
this.updateParts(v);
this.invalidateLinks();
// Add horizontal gravity
this.addHorizontalGravity(v, e);
this.setToCenter(v);
};
```
其中 addHorizontalGravity 函数的实现如下:
```
ContinuousForceDirectedLayout.prototype.addHorizontalGravity = function(vertexes, edges) {
var gravity = this.horizontalGravity;
for (var i = 0; i < vertexes.length; i++) {
var v = vertexes[i];
for (var j = i + 1; j < vertexes.length; j++) {
var u = vertexes[j];
if (!v || !u) continue;
var dx = u.location.x - v.location.x;
var dy = u.location.y - v.location.y;
var d = Math.sqrt(dx * dx + dy * dy);
var fx = dx * gravity;
var fy = dy * gravity;
v.dx += fx;
v.dy += fy;
u.dx -= fx;
u.dy -= fy;
}
}
};
```
这个函数会遍历所有的节点对,并计算它们之间的横向引力,然后添加到节点的 dx 和 dy 属性中。最后在 iterateLayout 函数中,这个 dx 和 dy 属性会被用来更新节点的位置。
阅读全文