Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get coordinates of mouse click on svg using d3

I want to get the coordinates of a mouse click on a rectangular shaped svg. I'm trying to print the mouse click coordinates to the console.

I can use pageX and pageY to get the coordinates, but that is of the entire page. I just need the coordinates inside the svg.

I'm using d3.v3.min.js

So I tried:

$(document).mousedown(function () {
     console.log(d3.mouse(this));
});

I get the error:

Uncaught TypeError: Cannot read property 'sourceEvent' of null

I also tried:

$(document).mousedown(function () {
     console.log(d3.mouse(document.getElementById("svg_id")));
});

I get the same error.

When I try with d3.svg.mouse(this), I get error:

Uncaught TypeError: undefined is not a function

How can I get the click coordinates in the svg and why are these d3.mouse() functions not working?

like image 721
brno792 Avatar asked Dec 11 '14 18:12

brno792


1 Answers

The problem with your code is that you're using jQuery event handling instead of D3 event handling. You want something like the following:

var svg = d3.select("svg");
svg.on("click", function() {
    console.log(d3.mouse(svg.node));
})
like image 70
Stephen Thomas Avatar answered Oct 15 '22 22:10

Stephen Thomas