前言
在3D力导向图中,我们有时需要展示节点之间的双向关系。默认情况下,3d-force-graph只能显示单向关系,即从一个节点指向另一个节点。但是,在某些场景下,我们需要同时展示节点之间的双向关系。比如,在社交网络分析或物流网络可视化中,这种需求非常常见。
在本篇博客中,我们将介绍如何在3D力导向图中设置双向关系样式。在此之前,您需要了解一些基本知识,例如HTML、CSS和JavaScript等。让我们开始吧!
创建3D力导向图
首先,让我们创建一个简单的3D力导向图,并设置一些节点和单向链接。这里,我们使用ForceGraph3D()函数来创建3D力导向图,并声明一些节点和链接数据:
``` const nodes = [ { id: 'node1', name: 'Node 1' }, { id: 'node2', name: 'Node 2' }, { id: 'node3', name: 'Node 3' }, ];
const links = [ { source: 'node1', target: 'node2' }, { source: 'node2', target: 'node3' }, ];
const Graph = ForceGraph3D() .graphData({ nodes, links }) .linkColor('#aaa') .linkOpacity(0.8) .linkWidth(2);
Graph(document.getElementById('my-3d-graph')); ```
这段代码将创建一个包含三个节点和两个链接的3D力导向图,并且链接的颜色、透明度和宽度都已设置。
设置双向关系样式
接下来,让我们修改代码以展示双向关系。对于每个链接,我们可以添加一个属性direction: 'both'来指示这是一个双向链接。例如:
const links = [ { source: 'node1', target: 'node2', direction: 'both' }, { source: 'node2', target: 'node3' }, ];
现在,我们需要使用linkThreeObject()回调函数来为每个链接设置自定义的3D对象。具体而言,我们需要使用箭头来表示双向关系。以下是完整的代码:
``` const Graph = ForceGraph3D() .graphData({ nodes, links }) .linkThreeObject((link) => { const isBidirectional = link.direction === 'both'; // 是否为双向链接 const color = isBidirectional ? '#f00' : '#aaa'; const opacity = isBidirectional ? 0.8 : 0.6; const width = isBidirectional ? 4 : 2;
// 创建箭头
const arrow = new THREE.Mesh(
new THREE.CylinderGeometry(0, 0.1, 0.3, 5),
new THREE.MeshBasicMaterial({ color })
);
arrow.rotation.z = Math.PI / 2;
arrow.position.set(0, 0, -1);
// 创建线条
const geometry = new THREE.CylinderGeometry(width, width, link.distance || 1, 5, 1, true);
const material = new THREE.MeshBasicMaterial({ color, transparent: true, opacity });
const cylinder = new THREE.Mesh(geometry, material);
// 创建组合
const group = new THREE.Group();
group.add(cylinder);
if (isBidirectional) {
group.add(arrow.clone());
group.add(arrow.clone().rotation.z += Math.PI);
}
return group;
});
Graph(document.getElementById('my-3d-graph')); ```
总结
在这段代码中,我们首先判断每个链接是否是双向的。如果是,则使用红色和较粗的线条表示;否则,使用灰色和较细的线条表示。
然后,我们创建一个箭头THREE.Mesh对象,并将其旋转90度。我们还创建了一个带有空心中心的圆柱体THREE.Mesh对象,代表链接线