删除路径完全填充在D3中



我当前正在构建一个平台,用于映射某些数据,这些数据需要在地图中的节点之间绘制线路。目前,我已经创建了这些行(图1(fill: none((。此外,我打算将单击侦听器添加到我也完成的行中。不幸的是,该路径似乎也有一个填充区域,它也听到事件并重叠在其他路径上,这使得无法单击其下方的路径(图2默认填充attr(。我试图设置fill: none(如第一张图片所示(,但似乎仅删除颜色,而不是填充区域。这是我添加行的代码:

function createPath(company) {
  //Create Paths Line
  var linePathGenerator = d3.line()
    .x(function(d) {
      return d.x;
    })
    .y(function(d) {
      return d.y;
    })
    .curve(d3.curveMonotoneX);
  // Add Path to the Line Layer
  var svgPath = layerArc.append("path")
    .attr("stroke", companyConfig[company].color)
    .attr("stroke-width", "1.5px")
    .attr("fill", "none")
    .style("opacity", 0.6);

  var d = linePathGenerator(adjency[company])
  var line = svgPath.attr("d", d)
  // Click Listener 
  line
    .on('click', function() {
      if (!d3.select(this).classed("active")) {
        layerArc.selectAll('path')
          .attr("stroke-width", "1.5px")
          .style("opacity", 0.6);
        d3.select(this)
          .attr("stroke-width", 3)
          .style("opacity", 1)
          .attr("class", "active")
        d3.selectAll(".nodes svg circle")
          .style("stroke", 'none')
        var circles = d3.selectAll(".nodes svg")
        circles = circles.filter(function(d) {
          return d.value.company == company
        })
        circles.select('circle').style("stroke", 'white')
          .style("stroke-width", 2)
      } else {
        layerArc.selectAll('path')
          .attr("stroke-width", "1.5px")
          .style("opacity", 0.6)
          .attr("class", "deactive")
        d3.selectAll(".nodes svg circle")
          .style("stroke", 'none')
      }
    })
  var totalLength = svgPath.node().getTotalLength();
  svgPath
    .attr("stroke-dasharray", totalLength + " " + totalLength)
    .attr("stroke-dashoffset", totalLength)
    .transition()
    .duration(4000)
    .ease(d3.easeLinear)
    .attr("stroke-dashoffset", 0)
}

有人知道如何完全删除填充物吗?或关于我如何以相同方式绘制线路但没有路径的任何其他建议?

在我看来,当用户单击路径的 stroke 时,您只希望听众发射,而不是在其 fill上(由于您使用术语" line" 而出现混乱,这意味着SVG中的另一件事(。

如果正确的解决方案很简单,您只需要将这些路径的指针设置为visibleStrokestroke

.attr("pointer-events", "visibleStroke");

这是一个演示,您可以单击填充或路径外,什么也没发生,请单击其中风,然后侦听器发射:

var svg = d3.select("svg");
var path = svg.append("path")
  .attr("d", "M50,20 L250,20 L250,130 L50,130 Z")
  .style("fill", "teal")
  .style("stroke", "black")
  .style("stroke-width", 4)
  .attr("pointer-events", "visibleStroke")
  .on("click", function() {
    console.log("clicked")
  });
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg></svg>

另外,值得一提的是,您的代码中有问题:如果将填充设置为 none,则默认的 pointer-events应该不是 fire。这是一个演示:

var svg = d3.select("svg");
var path = svg.append("path")
  .attr("d", "M50,20 L250,20 L250,130 L50,130 Z")
  .style("fill", "none")
  .style("stroke", "black")
  .style("stroke-width", 4)
  .on("click", function() {
    console.log("clicked")
  });
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg></svg>

最新更新