简体   繁体   中英

d3 force layout fixed links between nodes

I have a piece of code to display a force diagram which can be found in this link - https://jsfiddle.net/u49s9sth/3/

In the above case source data is represented as

var nodes = [{
    id: 0,
    reflexive: false,
    "x": 169,
    "y": 110,
    name: "event"
  }, {
    id: 1,
    reflexive: false,
    "x": 369,
    "y": 110,
    name: "email"
  }],
  lastNodeId = 1,
  links = [{
    source: {
    id: 0,
    reflexive: false,
    "x": 169,
    "y": 110,
    name: "event"
  },
    target: {
    id: 1,
    reflexive: false,
    "x": 369,
    "y": 110,
    name: "email"
  },
    left: false,
    right: true
  }];

In this case the link between the nodes shrinks after it is displayed to a smaller size. But with the same code , if i give the source data as

var nodes = [{
    id: 0,
    reflexive: false,
    "x": 169,
    "y": 110,
    name: "event"
  }, {
    id: 1,
    reflexive: false,
    "x": 369,
    "y": 110,
    name: "email"
  }],
  lastNodeId = 1,
  links = [{
    source: nodes[0],
    target: nodes[1],
    left: false,
    right: true
  }];

That is referring the data from nodes directly it will work fine - Here is the fiddle for the actual result- https://jsfiddle.net/u49s9sth/4/

Why does this happen ? How can i achieve the second result by giving data directly ?

In your first block of data the link is not really a link because with the way you specify the data d3 never actually has it connect the two nodes. It then just ends up behaving like a node, subject to the forces in layout and it shrinks away from the nodes.

So, how do we get it to behave like a true link? You are kind of limited here and you have two options on how to give d3 the data. The first is how you have it in your second snippet, specify source and target as node objects. The second is specify source and target as indexes into the nodes array:

var nodes = [{
    id: 0,
    reflexive: false,
    "x": 169,
    "y": 110,
    name: "event"
  }, {
    id: 1,
    reflexive: false,
    "x": 369,
    "y": 110,
    name: "email"
  }],
  lastNodeId = 1,
  links = [{
    source: 0, 
    target: 1,
    left: false,
    right: true
   }];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM