d3.js force directed layout constrained by a shape

為{幸葍}努か 提交于 2019-12-03 07:56:02
Frank van Wijk

Your idea is mine too. In the tick function you could add additional forces. This is my suggestion (not tested):

force.on('tick', function(e) {

  node
    .each(calcBorderDistance)
    .attr('transform', function(d) {
      d.x -= e.alpha*(1/Math.pow(d.borderDistance.x,2);
      d.y -= e.alpha*(1/Math.pow(d.borderDistance.y,2);
      return 'translate(' + d.x + ',' + d.y + ')'; // Move node
    });
});

function calcBorderdistance(d) {
  // Insert code here to calculate the distance to the nearest border of your shape
  var x = ..., y = ...;
  d.borderDistance = {'x':x,'y':y};
}

I have the inverse quadratic distance to the nearest border function loosely based on the formulas in excelent paper Drawing Graphs Nicely using Simulated Annealing. Following picture illustrates how methods from this paper affect drawing nodes bounded by a box:

And this picture illustrate case with different constraints, involving links between nodes:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!