使一条线为实线,其中一部分为虚线

时间:2016-01-25 18:50:22

标签: javascript d3.js

我想知道是否有将"stroke-dasharray"应用于路径的替代方法。我要做的是在路径中的某个范围添加一条虚线。事情是这条线不直。我想避免使用不同范围内的相同数据创建两条线。有没有人有想法?

enter image description here

2 个答案:

答案 0 :(得分:6)

我链接了这个question,它提供了stroke-dasharray如何工作的非常好的概述,但这个问题的有趣部分变成了,我怎么能突破这一行的特定部分?考虑到这一点,假设我们有一条从0到10的线,我们想要从2.5到7划线:

<!DOCTYPE html>
<meta charset="utf-8">
<style>
  body {
    font: 10px sans-serif;
  }
  
  .axis path,
  .axis line {
    fill: none;
    stroke: #000;
    shape-rendering: crispEdges;
  }
  
  .x.axis path {
    display: none;
  }
  
  .line {
    fill: none;
    stroke: steelblue;
    stroke-width: 1.5px;
  }
</style>

<body>
  <script src="//d3js.org/d3.v4.min.js"></script>
  <script>
    var margin = {
        top: 20,
        right: 20,
        bottom: 30,
        left: 50
      },
      width = 960 - margin.left - margin.right,
      height = 500 - margin.top - margin.bottom;

    var data = d3.range(11).map(function(d, i) {
      return {
        x: i,
        y: Math.random() * 100
      };
    });

    var x = d3.scaleLinear()
      .range([0, width])
      .domain([0, 10]);

    var y = d3.scaleLinear()
      .range([height, 0])
      .domain([0, 100]);

    var xAxis = d3.axisBottom()
      .scale(x);

    var yAxis = d3.axisLeft()
      .scale(y);

    var line = d3.line()
      .x(function(d) {
        return x(d.x);
      })
      .y(function(d) {
        return y(d.y);
      })
      .curve(d3.curveBasis);

    var svg = d3.select("body").append("svg")
      .attr("width", width + margin.left + margin.right)
      .attr("height", height + margin.top + margin.bottom)
      .append("g")
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis);

    svg.append("g")
      .attr("class", "y axis")
      .call(yAxis)

    var p = svg.append("path")
      .datum(data)
      .attr("class", "line")
      .attr("d", line);

    // draw dashed from 2.7 to 7 in the X domain
    var dashBetweenX = [2.5, 7]
        path = p.node(),
        totalLen = path.getTotalLength();
    
    // find the corresponding line lengths
    var dashBetweenL = dashBetweenX.map(function(d,i){
      
      var beginning = 0,
          end = totalLen,
          target = null,
          d = x(d);
      
      // find the line lengths the correspond to our X values
      // stolen from @duopixel from http://bl.ocks.org/duopixel/3824661
      while (true){
        target = Math.floor((beginning + end) / 2);
        pos = path.getPointAtLength(target);
        if ((target === end || target === beginning) && pos.x !== d) {
            break;
        }
        if (pos.x > d) end = target;
        else if (pos.x < d) beginning = target;
        else break; //position found
      }
      
      return target;
    })
    
    // draw the dashes
    var sd =  dashBetweenL[0],
        dp = dashBetweenL[0],
        count = 0;
    while (dp < dashBetweenL[1]){
      dp += 2;
      sd += ", 2";
      count++;
    }
    // per answer below needs odd number of dash array
    if (count % 2 == 0)
      sd += ", 2";   
    sd += ", " + (totalLen - dashBetweenL[1]);
    p.attr("stroke-dasharray", sd);    
  </script>
</body>

</html>

答案 1 :(得分:1)

@Mark为我提供了部分解决方案。添加破折号后,我不得不再执行一次检查。如果添加的破折号数为偶数,则破折号后面的行将不会渲染。

按如下方式修改该部分为我修好了:

let count = 0;
while (dp < dashBetweenL[1]) {
    count ++;
    dp += 4;
    sd += ", 4";
}

if (count % 2 == 0) {
    sd += ", 4, " + (totalLen - dashBetweenL[1]);
} else {
    sd += ", " + (totalLen - dashBetweenL[1]);
}
p.attr("stroke-dasharray", sd);

说实话,我很难理解为什么它有必要,但似乎工作得很好。