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?
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.
Mouse Movement The moveTo() function will move the mouse cursor to the X and Y integer coordinates you pass it.
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
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