随机生成力布局D3js

时间:2014-04-23 20:24:57

标签: javascript d3.js

我尝试使用d3js随机生成多个点,然后在保持不断移动的同时随机添加和删除连接。以下是我到目前为止的情况:

<meta charset="utf-8">
<style>

.link {
  stroke: #000;
  stroke-width: 1.5px;
}

.node {
  fill: #000;
  stroke: #fff;
  stroke-width: 1.5px;
}

.node.a { fill: #1f77b4; }
.node.b { fill: #ff7f0e; }
.node.c { fill: #2ca02c; }

</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>



var color = d3.scale.category10();

var nodes = [],
    links = [];

var force = d3.layout.force()
    .nodes(nodes)
    .links(links)
    .charge(-900)
    .linkDistance(220)
    .on("tick", tick);

var svg = d3.select("body").append("svg");

var node = svg.selectAll(".node"),
    link = svg.selectAll(".link");
    resize();
  d3.select(window).on("resize", resize);
function resize() {
    width = window.innerWidth, height = window.innerHeight;
    svg.attr("width", width).attr("height", height);
    force.size([width, height]).resume();
  }
// 1. Add three nodes and three links.
setTimeout(function() {
  var a = {id: "a"}, b = {id: "b"}, c = {id: "c"};
  nodes.push(a, b, c);
  links.push({source: a, target: b}, {source: a, target: c}, {source: b, target: c});
  start();
}, 0);

// 2. Remove node B and associated links.
setTimeout(function() {
  nodes.splice(1, 1); // remove b
  links.shift(); // remove a-b
  links.pop(); // remove b-c
  start();
}, 3000);

// Add node B back.
setTimeout(function() {
  var a = nodes[0], b = {id: "b"}, c = nodes[1];
  nodes.push(b);
  links.push({source: a, target: b}, {source: b, target: c});
  start();
}, 6000);

function start() {
  link = link.data(force.links(), function(d) { return d.source.id + "-" + d.target.id; });
  link.enter().insert("line", ".node").attr("class", "link");
  link.exit().remove();

  node = node.data(force.nodes(), function(d) { return d.id;});
  node.enter().append("circle").attr("class", function(d) { return "node " + d.id; }).attr("r", 8);
  node.exit().remove();

  force.start();
}

function tick(d) {
    console.log('tick')
    var randomX = d3.random.normal(width / 2, 80),
    randomY = d3.random.normal(height / 2, 80);
     d.x = randomX();
  d.y = randomY();
  console.log(d.y);
  node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })

  link.attr("x1", function(d) { return d.source.x; })
      .attr("y1", function(d) { return d.source.y; })
      .attr("x2", function(d) { return d.target.x; })
      .attr("y2", function(d) { return d.target.y; });
}

</script>

我从here得到的代码大多数。基本上我试图创建类似于this示例的东西,但不是使用hexbin,我只是想随机生成并移动节点/圆圈。与this page上的功能类似的东西,其中节点不断移动和更改链接。任何有关如何实现此功能的帮助将不胜感激。这里还有jsfiddle到目前为止的内容。

0 个答案:

没有答案