我使用d3繪製線圖。我想要做的是找到一個垂直移動線與兩個線圖的交點。d3.js:垂直移動線與兩個線圖的交點
現在,小提琴中的代碼只能找到一個圖形的交點。
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/我已經做到了,但圖2上的點並不完全在同一行上,它是在垂直線前面的一些像素,並且在第二張圖上的鼠標移動不起作用,而我已經寫入整個矩形的代碼。 – asdfdefsad