如何在强制布局中动态附加箭头标记 d3.js

How to append the arrow marker dynamically in force layout d3.js

如何在 d3.js 的强制布局中动态附加箭头标记,如下图所示

  d3.select('svg.svgparentTag').selectAll("marker").data(["BLACK", "BLUE"]).enter().append("svg:marker")
        .attr("id", String)
        .attr("viewBox", "0 -5 10 10")
        .attr("markerWidth", 6)
        .attr("markerHeight", 6)
        .attr("orient", "auto")
        .append("svg:path")
        .attr("class", function(d) { return "marker_only " + d.type; })
        .attr("d", "M0,-5L10,0L0,5"); //marker 

 var path = d3.select('.pitch').selectAll("path")
            .data(force.links())
            .enter().append('g').classed('g_path', true).append("svg:path").attr("class", "link");


 path.filter(function(d) {
            return d.arrow == true;
        }).attr("marker-mid", function(d) { return "url(#BLUE)"}).attr("stroke-linecap", "round");

http://bl.ocks.org/mbostock/1153292

中有一个这样的例子

您需要做的是创建 svg:defs 并在 defs 中放置 svg:marker 个元素。然后使用 marker-endmarker-midmarker-start

属性之一附加标记
// Per-type markers, as they don't inherit styles.
svg.append("defs").append("marker")
    .attr("id", "marker")
    .attr("viewBox", "0 -5 10 10")
    .attr("refX", 15)
    .attr("refY", -1.5)
    .attr("markerWidth", 6)
    .attr("markerHeight", 6)
    .attr("orient", "auto")
  .append("path")
    .attr("d", "M0,-5L10,0L0,5");

var path = svg.append("g").selectAll("path")
    .data(force.links())
  .enter().append("path")
    .attr("marker-end", "url(#marker)"; });

如果您需要直线的标记中点,如果路径中间没有节点,您可能 运行 遇到标记不在中间绘制的问题。看看 talkol 的回答如何解决这个

根据该问题中已接受的答案改编,您可以有一个像这样的生成器函数,它生成中间有节点的线或基于 d.type 的弧。在 jsfiddle

上查看
function tick() {
  path.attr("d", function(d) {
    var dx = d.target.x - d.source.x,
        dy = d.target.y - d.source.y,
        dr = Math.sqrt(dx * dx + dy * dy)/4,
        mLx = d.source.x + dx/2,
        mLy = d.source.y + dy/2,
        mAx = d.source.x + dx,
        mAy = d.source.y + dy;
      if (d.type === "line") {
       return [
          "M",d.source.x,d.source.y,
           "L",mLx,mLy,
           "L",d.target.x,d.target.y,
           "Z"
          ].join(" ");
      }
    return [
      "M",d.source.x,d.source.y,
      "A",dr,dr,0,0,1,mAx,mAy,
      "A",dr,dr,0,0,1,d.target.x,d.target.y
    ].join(" ");
  });