Cenoc
Cenoc

Reputation: 11680

Get location along a path or line upon click in d3

As stated in the title, I was wondering how to catch the location along a path or line of a mouse click - is it simply using the mousedown event and then calculating the d3.event.pageX, d3.event.pageY as it matches the line? Is there a better way?

Upvotes: 1

Views: 2252

Answers (1)

Gilsha
Gilsha

Reputation: 14589

Use d3.mouse function.

d3.mouse(container)

Returns the x and y coordinates of the current d3.event, relative to the specified container. The container may be an HTML or SVG container element, such as an svg:g or svg:svg. The coordinates are returned as a two-element array [x, y].

Reference: https://github.com/mbostock/d3/wiki/Selections#d3_mouse

Example: (Try clicking on the path)

var points = [
  [480, 200],
  [580, 400],
  [680, 100],
  [780, 300],
  [180, 300],
  [280, 100],
  [380, 400]
];

var svg = d3.select("body").append("svg")
  .attr("width", 960)
  .attr("height", 500);

var path = svg.append("path")
  .data([points])
  .attr("d", d3.svg.line()
    .tension(0) // Catmull–Rom
    .interpolate("cardinal-closed"));

var circle = svg.append("circle")
  .attr("r", 5)
  .style("fill", "red")
  .attr("cx", points[0][0])
  .attr("cy", points[0][1]);

path.on("click", function() {
  circle.attr("cx", d3.mouse(this)[0])
    .attr("cy", d3.mouse(this)[1]);
});
path {
  fill: none;
  stroke: black;
  stroke-width: 5;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

Upvotes: 4

Related Questions