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?
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));
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With