Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding "mouseover" events to points on a line in d3.js

I would like to get the coordinates of a point on a line by clicking on the line using the following code:

var lineData = [ { "x": 1,   "y": 5},  { "x": 20,  "y": 20},
                 { "x": 40,  "y": 10}, { "x": 60,  "y": 40},
                 { "x": 80,  "y": 5},  { "x": 100, "y": 60}];

var lineFunction = d3.svg.line()
    .x(function(d) { return d.x; })
    .y(function(d) { return d.y; })
    .interpolate("linear");

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

var lineGraph = svgContainer.append("path")
    .data([lineData]).attr("d", lineFunction)
  //.attr("d", lineFunction(lineData))  
    .attr("stroke", "blue")
    .attr("stroke-width", 2)
    .attr("fill", "none")
    .on('mousedown', function(d) {
        console.log({"x":d.x, "y":d.y})
    });

(I updated the code to address the comments, but I still get "Object {x: undefined, y: undefined}")

I keep getting an "undefined" when clicking on the line. Am I missing a step?

like image 570
vgoklani Avatar asked Jan 14 '23 02:01

vgoklani


1 Answers

You can get the coordinates of an event using d3.event:

.on("mousedown", function() {
    console.log({"x": d3.event.x, "y": d3.event.y});
});
like image 137
Lars Kotthoff Avatar answered Jan 22 '23 09:01

Lars Kotthoff