I have a graph, and I want the line representing the graph to show a circle at the x coordinate when hovering on top of the svg area. This circle should follow the path of the line that represents the curve. The problem is that I don’t know how to do this.
The code below shows how far I have succeded, and it indeed adds a circle to the document at the right x coordinate. Now, what do I replace the question mark with?
svg.on("mousemove", function() {
d3.select("path.line")
.style("stroke-width", "2.5px");
svg.append("svg:circle")
.attr("cx", Math.floor(event.offsetX-m[1]))
.attr("cy", ?)
.attr("r", "10")
.attr("fill", "red");
});
SVG provides a native function called
.getPointAtLength()which returns a the x and y values of a path at any length you pass at it.You would need to iterate through the length of the line until you find the corresponding y position. Here is how you would do it in D3:
You can see a demo here: http://bl.ocks.org/3824661