d3.js从一条路径绘制多条并行路径

时间:2016-04-29 12:36:46

标签: javascript d3.js

我正在尝试根据一组坐标绘制多个并行路径,如本示例所示

Non overlapping lines

这是我的代码,它与我的期望完全不同,因为线条重叠。我试图让它工作,但我不知道我应该使用什么样的偏移计算。这就是我得到的

Overlapping lines

(function ($) {
  $(document).ready(function()
  {
    var wHeight = $(window).height();

   //The SVG Container
   var svgContainer = d3.select("#d3-line").append("svg")
                                        .attr("width", 1000)
                                        .attr("height", wHeight);

   var lineData = [ { "x": 100, "y": wHeight / 2 },  { "x": 300,  "y": (wHeight / 2) - 150 },
                    { "x": 600,  "y": wHeight / 2 }, { "x": 900,  "y": (wHeight / 2) - 250 },
                    { "x": 1200,  "y": (wHeight / 2) },  { "x": 1500, "y": (wHeight / 2) + 150}];


    // https://www.dashingd3js.com/svg-paths-and-d3js
    //This is the accessor function we talked about above
    var lineFunction = d3.svg.line()
                             .x(function(d) { return d.x; })
                             .y(function(d) { return d.y; })
                            .interpolate("monotone");

   //The line SVG Path we draw
   var lineGraph = svgContainer.append("path")
                               .attr("d", lineFunction(lineData))
                               .attr("stroke", "#00abc8")
                              //  .style("stroke-dasharray", ("1, 10"))
                               .style("stroke-linecap", "round")
                               .attr("stroke-width", 2)
                               .attr("fill", "none");


  var lineFunction2 = d3.svg.line()
                            .x(function(d) { return d.x + 4; })
                            .y(function(d) { return d.y + 4; })
                           .interpolate("monotone");

  //The line SVG Path we draw
  var lineGraph2 = svgContainer.append("path")
                              .attr("d", lineFunction2(lineData))
                              .attr("stroke", "#00abc8")
                             //  .style("stroke-dasharray", ("1, 10"))
                              .style("stroke-linecap", "round")
                              .attr("stroke-width", 2)
                              .attr("fill", "none");

  });
})(jQuery);
<!DOCTYPE html>

<html lang="en-GB">
<head>
	<meta charset="utf-8">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
  <div id="d3-line"></div>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

您可以克隆原始路径并应用翻译。 E.g。

var newPath = svgGroup.append("svg:path").attr("d", function() {
         return origPath.attr('d');
    })
    .attr("transform", "translate(4,4)");