d3.js:垂直移动线与两个线图的交点

时间:2013-12-16 06:12:39

标签: javascript d3.js

我正在使用d3绘制折线图。我想要做的是找到一条垂直移动线与两个折线图的交点。

现在,小提琴中的代码能够找到只有一个图形的交叉点。

rect.on('mousemove', function () {

 var xPos = d3.mouse(this)[0];
d3.select(".verticalLine").attr("transform", function () {
 return "translate(" + xPos + ",0)";
});


 var pathLength = mainLine.node().getTotalLength();
  var x = xPos;
 var beginning = x,
  end = pathLength,
  target;
 while (true) {
 target = Math.floor((beginning + end) / 2);
 pos = mainLine.node().getPointAtLength(target);
 if ((target === end || target === beginning) && pos.x !== x) {
     break;
 }
 if (pos.x > x) end = target;
else if (pos.x < x) beginning = target;
else break; //position found
 }
         circle.attr("opacity", 1)
          .attr("cx", x)
         .attr("cy", pos.y);


    console.log("x and y coordinate where vertical line intersects graph: " + [pos.x, pos.y]);
   console.log("data where vertical line intersects graph: " + [xScale.invert(pos.x), yScale.invert(pos.y)]);
});

http://jsfiddle.net/2SURM/

1 个答案:

答案 0 :(得分:1)

你必须改变

<div id="graph1" class="aGraph" style="position:absolute;top:300px;"></div>

<div id="graph1" class="aGraph" style="position:absolute;top:300px; left:0; float:left;"></div>

现在图2与图1在同一行。这里是小提琴 - http://jsfiddle.net/2SURM/2/

这是在第二张图上使用鼠标移动的小提琴。我在第二张图后面添加了第二个rect。 http://jsfiddle.net/cuckovic/2SURM/3/