3d力导向图设置节点间双向关系

前言

在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对象,代表链接线

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱划水de鲸鱼哥~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值