Reputation: 998
I need to get X and Y coordinate values from the mouse location inside SVG. I created an example here. For mousemove
function I want x and y coordinate position printed (scaled according to the data values from the mouse position). I tried using the invert function - but that doesn't work either. Can someone please help me to figure out how to get x and y coordinate values from mouse position? I am using d3 version 3.
svg.on("mousemove", function() {
console.log("x", d3.mouse(this)[0]);
console.log("y", d3.mouse(this)[1]);
console.log("x - using invert", xscale.invert(d3.event.pageX));
console.log("y- using invert", yscale.invert(d3.event.pageY));
});
Upvotes: 3
Views: 7402
Reputation: 102174
You have a couple of problems. First, use d3.mouse
instead of d3.event.pageX
or pageY
.
But the biggest problem is that you're setting the listener to the whole SVG and expecting to see the values according to the domain in the axes. That's not the adequate approach. However, if you want to stick with that, you have to add the translate values for those axes. In this case, 50 and 10:
console.log("x - using invert", xscale.invert(d3.mouse(this)[0] - 50));
console.log("y- using invert", yscale.invert(d3.mouse(this)[1] - 10));
Here is your code with that change:
var width = 400,
height = 500;
var data = [10, 15, 20, 25, 30];
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height)
var xscale = d3.scale.linear()
.domain([0, d3.max(data)])
.range([0, width - 100]);
var yscale = d3.scale.linear()
.domain([0, d3.max(data)])
.range([height / 2, 0]);
svg.on("mousemove", function() {
console.log("x - using invert", xscale.invert(d3.mouse(this)[0] - 50));
console.log("y- using invert", yscale.invert(d3.mouse(this)[1] - 10));
});
var x_axis = d3.svg.axis()
.scale(xscale).orient("bottom");
var y_axis = d3.svg.axis()
.scale(yscale).orient("left");;
svg.append("g")
.attr("transform", "translate(50, 10)")
.call(y_axis);
var xAxisTranslate = height / 2 + 10;
svg.append("g")
.attr("transform", "translate(50, " + xAxisTranslate + ")")
.call(x_axis)
.as-console-wrapper { max-height: 20% !important;}
path {
fill: none;
stroke: black;
shape-rendering: crispEdges;
}
line {
shape-rendering: crispEdges;
stroke: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
Upvotes: 11