D3 js图中箭头和相同颜色的链接

时间:2018-07-11 20:01:25

标签: javascript html css d3.js

我是D3的新手,并一直在尝试使箭头的颜色与D3图中箭头的颜色相同,这是指给定here的代码解决方案。

它是一个有向图,而json文件负责链接各个节点。我试图确保无论链接的颜色是什么,我的箭头都具有相同的颜色,但这似乎不起作用。这是我的js代码:

var width = 960,
height = 500;

// initialization
var svg = d3.select("div").append("svg")
    .attr("width", width)
    .attr("height", height);

var force = d3.layout.force()
    .gravity(0) // atom's cohesiveness / elasticity of imgs :)
    .distance(150) // how far the lines ---> arrows :)
    .charge(-50) // meta state transition excitement
    .linkDistance(140)
    //.friction(0.55) // similar to charge for quick reset :)
    .size([width, height]); // degree of freedom to the canvas

// exception handling
d3.json("/assets/javascripts/position.json", function(error, json) {
     if (error) throw error;
          // Restart the force layout
    force
      .nodes(json.nodes)
      .links(json.links)
      .start();

      var pipeline = document.getElementById("pipeline").innerHTML;

      // Build the link
      var link = svg.selectAll(".links")
      .data(json.links)
      .enter().append("line")
      .attr("class", "lol")
      .style("stroke-width", "2")
      .attr("stroke", function(d){
        return linkColor(d.colorCode);})
      .each(function(d) {
        var color = linkColor(d.colorCode);
        d3.select(this).attr("marker-end", marker(color));
      });

      function marker(color) {
        svg.append("svg:marker")
          .attr("id", color.replace("#", ""))
          .attr("viewBox", "0 -5 10 10")
          .attr("refX", 15)
          .attr("refY", 0)
          .attr("markerWidth", 9)
          .attr("markerHeight", 9)
          .attr("orient", "auto")
          .attr("markerUnits", "userSpaceOnUse")
          .append("svg:path")
          .attr("d", "M0,-5L10,0L0,5")
          .style("fill", linkColor(color));

        return "url(" + linkColor(color) + ")";
      };
      var node = svg.selectAll(".nodes")
      .data(json.nodes)
      .enter().append("g")
      .attr("class", "node")
      .call(force.drag);

      node.append("svg:image")
                  .attr("xlink:href", "") // update the node with the image
                  .attr("x", function(d) { return -5;}) // how far is the image from the link??
                  .attr("y", function(d) { return -25;}) // --- same ---
                  .attr("height", 55) // size
                  .attr("width", 55);

      // Define the div for the tooltip
      var div = d3.select("body").append("pre")
      .attr("class", "tooltip")
      .style("opacity", 0);

      node.append("text")
        .attr("class", "labelText")
        .attr("x", function(d) { return -5;})
        .attr("y", function(d) { return 48;})
        .text(function(d) { return d.label });

      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 + ")"; });

        force.stop();
      });

      function linkColor(linkCode) {
        switch (linkCode)
        {
          case 'ctoc':
            return '#0000FF';//blue
            break;
          case 'ctof':
            return '#00afaa';//green
            break;
          case 'ftoc':
            return '#fab800';//yellow
            break;
          case 'ftof':
            return '#7F007F';//purple
            break;
          default:
            return '#0950D0';//generic blue
            break;
        }
      }
});

其中position.json是:

    {
  "nodes": [
    {"x": 100, "y": 100},
    {"x": 250, "y": 100},
    {"x": 400, "y": 100},
    {"x": 550, "y": 200},
    {"x": 700, "y": 200},
    {"x": 100, "y": 300},
    {"x": 250, "y": 300},
    {"x": 400, "y": 300}
  ],
  "links": [
    {"source":  0, "target":  1, "colorCode" : "ctof"},
    {"source":  1, "target":  2, "colorCode" : "ftoc"},
    {"source":  2, "target":  3, "colorCode" : "ctof"},
    {"source":  3, "target":  4, "colorCode" : "ftoc"},
    {"source":  5, "target":  6, "colorCode" : "ctof"},
    {"source":  6, "target":  7, "colorCode" : "ftoc"},
    {"source":  7, "target":  3, "colorCode" : "ctof"}
  ]
}

但是我在屏幕上看不到任何输出。有人可以帮我确定我要去哪里了吗?

1 个答案:

答案 0 :(得分:5)

微小变化:

marker函数中,传递的参数(颜色)已经是相应标记的ID,这意味着您无需将其传递给linkColor函数。这是更改的标记功能:

function marker(color) {
    svg.append("svg:marker")
      ...
      .attr("refX", 10)
      ...
      .style("fill", color);

    return "url(" + color + ")";
  };

以下是使用上述代码的代码段,并回答了有关如何添加JSON的评论,您可以将其添加为变量(就像我在这里所做的那样,这也使调试更容易)。

var width = 960,
height = 500;

// initialization
var svg = d3.select("div").append("svg")
    .attr("width", width)
    .attr("height", height);

var force = d3.layout.force()
    .gravity(0) // atom's cohesiveness / elasticity of imgs :)
    .distance(150) // how far the lines ---> arrows :)
    .charge(-50) // meta state transition excitement
    .linkDistance(140)
    //.friction(0.55) // similar to charge for quick reset :)
    .size([width, height]); // degree of freedom to the canvas

// exception handling

var json =     {
  "nodes": [
    {"x": 100, "y": 100},
    {"x": 250, "y": 100},
    {"x": 400, "y": 100},
    {"x": 550, "y": 200},
    {"x": 700, "y": 200},
    {"x": 100, "y": 300},
    {"x": 250, "y": 300},
    {"x": 400, "y": 300}
  ],
  "links": [
    {"source":  0, "target":  1, "colorCode" : "ctof"},
    {"source":  1, "target":  2, "colorCode" : "ftoc"},
    {"source":  2, "target":  3, "colorCode" : "ctof"},
    {"source":  3, "target":  4, "colorCode" : "ftoc"},
    {"source":  5, "target":  6, "colorCode" : "ctof"},
    {"source":  6, "target":  7, "colorCode" : "ftoc"},
    {"source":  7, "target":  3, "colorCode" : "ctof"}
  ]
};

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

      // Build the link
      var link = svg.selectAll(".links")
      .data(json.links)
      .enter().append("line")
      .attr("class", "lol")
      .style("stroke-width", "2")
      .attr("stroke", function(d){
        return linkColor(d.colorCode);})
      .each(function(d) {
        var color = linkColor(d.colorCode);
        d3.select(this).attr("marker-end", marker(color));
      });

      function marker(color) {
        svg.append("svg:marker")
          .attr("id", color.replace("#", ""))
          .attr("viewBox", "0 -5 10 10")
          .attr("refX", 10)
          .attr("refY", 0)
          .attr("markerWidth", 9)
          .attr("markerHeight", 9)
          .attr("orient", "auto")
          .attr("markerUnits", "userSpaceOnUse")
          .append("svg:path")
          .attr("d", "M0,-5L10,0L0,5")
          .style("fill", color);

        return "url(" + color + ")";
      };
      var node = svg.selectAll(".nodes")
      .data(json.nodes)
      .enter().append("g")
      .attr("class", "node")
      .call(force.drag);

      node.append("svg:image")
                  .attr("xlink:href", "") // update the node with the image
                  .attr("x", function(d) { return -5;}) // how far is the image from the link??
                  .attr("y", function(d) { return -25;}) // --- same ---
                  .attr("height", 55) // size
                  .attr("width", 55);

      // Define the div for the tooltip
      var div = d3.select("body").append("pre")
      .attr("class", "tooltip")
      .style("opacity", 0);

      node.append("text")
        .attr("class", "labelText")
        .attr("x", function(d) { return -5;})
        .attr("y", function(d) { return 48;})
        .text(function(d) { return d.label });

      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 + ")"; });

        force.stop();
      });

      function linkColor(linkCode) {
        switch (linkCode)
        {
          case 'ctoc':
            return '#0000FF';//blue
            break;
          case 'ctof':
            return '#00afaa';//green
            break;
          case 'ftoc':
            return '#fab800';//yellow
            break;
          case 'ftof':
            return '#7F007F';//purple
            break;
          default:
            return '#0950D0';//generic blue
            break;
        }
      }
  <head>
    <link rel="stylesheet" href="style.css">
    <script src="https://d3js.org/d3.v3.min.js"></script>
  </head>

  <body>
      <div></div>
      
          <script src="script.js"></script>

  </body>

我进行了另一项更改(根据箭头的长度将refY更改为10)。试一试,看看有什么不同。 希望这会有所帮助。