Mouse position in D3
Solution 1:
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
Solution 2:
V3:
var svg = d3.select('body').append('svg')
.attr('width', 600)
.attr('height', 600)
.on('mousemove', function() {
console.log( d3.mouse(this) ) // log the mouse x,y position
});
V4 and V5:
var svg = d3.select('body').append('svg')
.attr('width', 600)
.attr('height', 600)
.on('mousemove', function() {
console.log( d3.event.pageX, d3.event.pageY ) // log the mouse x,y position
});
Solution 3:
You can understand the click and drag function through this example very well.Hope it will helps..
var point = d3.mouse(this)
, p = {x: point[0], y: point[1] };
http://jsfiddle.net/mdml/da37B/
Solution 4:
As commented above by chkaiser and The Composer the approach is different in version 6;
var coordinates = d3.pointer(this);
var x = coordinates[0];
var y = coordinates[1];
var svg = d3.select('body').append('svg')
.attr('width', 600)
.attr('height', 600)
.on('mousemove', (event) => {
var coords = d3.pointer( event );
console.log( coords[0], coords[1] ) // log the mouse x,y position
});
Further details @ D3 v6 migration guide