我对D3js比较陌生。我介绍了有关Udemy by Adam Janes的教程的基础。我想创建可以连接以下地图上的节点的多条单独的线。 绿点是节点,我想用一条线显示节点之间的连接。用于绘制节点的数据:
[
{
"_id": "5bd940c7c917bd051c995dca",
"whereID": "100110060000",
"SN": 67,
"position": [
1085.2642276422764,
564.0921409214093
],
"trainStatus": 0,
"missionSN": 1
},
...
{
"_id": "5bc6e4e5603d6112000e028a",
"whereID": "100110060000",
"SN": 32,
"position": [
1037.511770244821,
440.9957627118644
],
"trainStatus": 0,
"missionSN": 1
},
{
"_id": "5bc6e4e5603d6112000e0289",
"whereID": "100110060000",
"SN": 31,
"position": [
1181.314736346516,
357.909604519774
],
"trainStatus": 0,
"missionSN": 1
},
{
"_id": "5bc6e4e5603d6112000e0288",
"whereID": "100110060000",
"SN": 30,
"position": [
1433.7688323917137,
309.9752824858757
],
"trainStatus": 0,
"missionSN": 1,
"connectedNodes": [
{
"SN": 62,
"position": [
1459.3338041431261,
333.4098399246704
],
"whereID": "100110060000"
}
]
},
{
"_id": "5bc6e4e5603d6112000e0287",
"whereID": "100110060000",
"SN": 29,
"position": [
1702.201035781544,
308.91007532956684
],
"trainStatus": 0,
"missionSN": 1,
"connectedNodes": [
{
"SN": 61,
"position": [
1732.026836158192,
333.4098399246704
],
"whereID": "100110060000"
},
{
"SN": 62,
"position": [
1459.3338041431261,
333.4098399246704
],
"whereID": "100110060000"
}
]
},
...
]
利用上述数据,我试图使用position
值创建{x1,y1}值,并将它们与创建{x2,y2}的connectedNodes.position
值连接。我遇到的问题是,可以有多个connectedNodes
,那么如何画线呢?
这就是我所拥有的:
view = svg.append('svg')
.attr('width', '100%')
.attr('height', '100%')
.attr('class', 'view-container')
.append('g')
.attr('width', '100%')
.attr('height', '100%')
.attr('class', 'view')
nodeUpdate = view.selectAll('.trainingNode').data(useData);
nodeEnter = nodeUpdate.enter().append('g').attr('class', 'trainingNode');
nodeEnter
.append('line')
.attr('x1', d => {
if (d.connectedNodes && d.connectedNodes.length > 0)
return d.position[0]
})
.attr('x2', d => {
if (d.connectedNodes && d.connectedNodes.length > 0)
return d.position[0]
})
.attr('y1', d => {
if (d.connectedNodes && d.connectedNodes.length > 0)
return d.connectedNodes[0].position[0]
})
.attr('y2', d => {
if (d.connectedNodes && d.connectedNodes.length > 0)
d.connectedNodes[0].position[0]
})
.style('stroke', 'black')
.style('stroke-width', 5)
编辑:经过一段时间的阅读,我已经成功添加了将节点链接在一起的线,但是仅在画布的上半部分正确显示。
这是我使用的代码:
let links = []
useData.forEach(ud => {
if (ud.connectedNodes && ud.connectedNodes.length > 0) {
ud.connectedNodes.forEach(node => {
links.push({
source: node.SN,
target: ud.SN
})
})
}
})
let simulation = d3.forceSimulation()
.force('link', d3.forceLink().id(d => d.SN))
simulation.nodes(useData)
simulation.force('link')
.links(links)
let line = nodeEnter.append('line')
.data(links)
.attr('x1', d => Math.floor(d.source.position[0] * widthRatio))
.attr('y1', d => Math.floor(d.source.position[1] * widthRatio))
.attr('x2', d => Math.floor(d.target.position[0] * widthRatio))
.attr('y2', d => Math.floor(d.target.position[1] * widthRatio))
.style('stroke', 'black')
.style('stroke-width', 3)