弹跳不是强制布局

时间:2016-10-20 14:12:12

标签: javascript d3.js force-layout

我有四个节点显示为数据json中给出的位置。拖动每个节点后,我已设法将每个节点设置回其给定位置。它工作正常,但默认弹跳不起作用,而是快速设置到固定位置。为此提供一个弹跳效果,需要更改我的代码。

请看一下示例

<!DOCTYPE html>
<meta charset="utf-8">
<style>

.link {
  stroke: #dfdfdf;
}

.node text {
  pointer-events: none;
  font: 10px sans-serif;
}
.link.red {
    stroke: blue;
}

</style>




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

var width = 500,
    height = 500

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);


var force = d3.layout.force()
    .gravity(0)
    .linkDistance (200)
    .charge(0)
    .size([width, height]);

var node_psoition = [{"x":65, "y":43},{"x":365, "y":43},{"x":265, "y":243},{"x":65, "y":243}]
var datajson = {
  "nodes" : [ {"id":1,"name" : "a", "group" : 2, "x":65, "y":43 , "fixed":"TRUE"} , {"id":2,"name" : "b", "group" : 1,"x":265, "y":43, "fixed":"TRUE"}, { "id":3,"name" : "c", "group" : 1, "x":265, "y":243, "fixed":"TRUE" }, {"id":4,"name" : "d", "group" : 2,"x":65, "y":243, "fixed":"TRUE"} ],
  "links" : [{"source": 0 ,"target" : 1 , "value" : 1},{"source": 0 ,"target" : 3 , "value" : 1},{"source": 2 ,"target" : 3 , "value" : 1},
  {"source": 2 ,"target" : 1 , "value" : 1}
  ]
}


  force
      .nodes(datajson.nodes)
      .links(datajson.links)
      .start();


var drag = force.drag()
    .on("dragend", dragend);


  var link = svg.selectAll(".link")
      .data(datajson.links)
    .enter().append("line")
      .attr("class", "link");

  var node = svg.selectAll(".node")
      .data(datajson.nodes)
    .enter().append("g")
      .attr("class", "node")
      .call(force.drag);

  node.append("image")
      .attr("x", -8)
      .attr("y", -8)
      .attr("class", 'bounce')
      .attr("width", 45)
      .attr("height", 45)
      .attr("xlink:href", function(d) {
    var rnd = Math.floor(Math.random() * 64 + 1);
    var imagePath =
           "http://www.bigbiz.com/bigbiz/icons/ultimate/Comic/Comic"
           + rnd.toString() + ".gif";

    return imagePath;
});

  node.append("text")
      .attr("dx", 12)
      .attr("dy", ".35em")
      .text(function(d) { return d.name });

  force.on("tick", function() {
    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; });

    node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });


   });



  function dragend(d) {

        force.stop();
        position = (d.id - 1);
        temp_x = node_psoition[position].x;
        temp_y = node_psoition[position].y;

        d.x = d.px = temp_x;
        d.y = d.py = temp_y;
        d.fixed = true;
        force.start();

  }


</script>

为每个节点提供一个弹跳效果,需要更新我的代码。请指教。

由于

0 个答案:

没有答案