Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mouse position in D3

I just wanted to get the mouse position using D3 by using the following code:

var x = 0;  svg.on('mousemove', function () {    x = d3.mouse(this)[0];          }); 

but x is always equal to 0. By using console.log(), I can see that x value is getting changed just inside the function() but out of it x got its initial value of 0.

How can I save the x value and use it later in my application?

like image 443
I3i0 Avatar asked May 27 '13 10:05

I3i0


People also ask

What does D3 mouse return?

mouse() function in D3. js is used to return the x-coordinate and y-coordinate of the current event. If the event is clicked then it returns the x and y position of the click.

Which function can take mouse coordinates?

Mouse Movement The moveTo() function will move the mouse cursor to the X and Y integer coordinates you pass it.


1 Answers

You have to use an array. That will store x and y like:

var coordinates= d3.mouse(this); var x = coordinates[0]; var y = coordinates[1];  // D3 v4 var x = d3.event.pageX - document.getElementById(<id-of-your-svg>).getBoundingClientRect().x + 10 var y = d3.event.pageY - document.getElementById(<id-of-your-svg>).getBoundingClientRect().y + 10 
like image 184
Sudarshan Avatar answered Sep 30 '22 06:09

Sudarshan