在d3中单击按钮时淡出连接节点的颜色

时间:2018-01-14 12:13:09

标签: javascript d3.js svg graph visualization

我希望仅在节点与其他节点连接时,在JavaScript(d3.js)中按钮单击时更改颜色。 我关注此示例https://bl.ocks.org/mbostock/929623

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://d3js.org/d3.v3.min.js"></script>
<style>

rect {
  fill: none;
  pointer-events: all;
}

.node {
  fill: blue;
}

.link {
  stroke: #999;
}

</style>
</head>
<body>

<script>
var width = 960,
    height = 500;

var fill = d3.scale.category20();

var data = {nodes: [], links: []};

var force = d3.layout.force()
    .size([width, height])
    .nodes(data.nodes)
    .linkDistance(80)
    .charge(-60)
    .on("tick", tick);

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

svg.append("rect")
    .attr("width", width)
    .attr("height", height);

var nodes = force.nodes(),
    links = force.links(),
    node = svg.selectAll(".node"),
    link = svg.selectAll(".link");

restart();


function dblclick() {
  var point = d3.mouse(this),
      node = {x: point[0], y: point[1]},
      n = nodes.push(node);

  nodes.forEach(function(target) {

    var x = target.x - node.x,
        y = target.y - node.y;

    if (Math.sqrt(x * x + y * y) < 50) {
      links.push({source: node, target: target});
    }
  });

  restart();
}


function tick() {
  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("cx", function(d) { return d.x; })
      .attr("cy", function(d) { return d.y; });
}



//Toggle stores whether the highlighting is on
var toggle = 0;


function neighboring(a, b) {
  return links.forEach(function(d) {
    return (d.source === a && d.target === b)
        || (d.source === b && d.target === a);
  });

}



//change color after button click
d3.select("body").append("button").text("Next")
  .on("click", function() { 
          if (toggle == 0) {
        //Reduce the opacity of all but the neighbouring nodes
        d = d3.select(node);
        node.style("opacity", function (o) {
            return neighboring(d, o) ? 1 : 0.1;
        });
    //Reduce the opacity
        toggle = 1;
    } 
    else {
        //Put them back to opacity=1
        node.style("opacity", 1);
        link.style("opacity", 1);
        toggle = 0;
    }

  });


function restart() {
  link = link.data(links);

  link.enter().insert("line", ".node")
      .attr("class", "link");

  node = node.data(nodes);

  node.enter().insert("circle")
      .attr("class", "node")
      .attr("r", 10)
      .style("fill", "blue");

  force.start();
}

</script>
</body>

我添加了代码,它应该检查节点是否是邻居,但它似乎不起作用。单击按钮后,所有节点都在淡入淡出,不仅已连接。

0 个答案:

没有答案