59

我只是想通过使用以下代码使用 D3 获取鼠标位置:

var x = 0;

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

x总是等于0。通过使用console.log(),我可以看到x值在内部发生了变化,function()但在其中x得到了初始值0

如何保存该x值并稍后在我的应用程序中使用它?

4

6 回答 6

90

你必须使用一个数组。这将存储xy喜欢:

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
于 2013-05-27T10:10:30.430 回答
19

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 和 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
    });
于 2017-05-17T03:51:37.433 回答
16

你可以通过这个例子很好地理解点击和拖动功能。希望它会有所帮助..

 var point = d3.mouse(this)
  , p = {x: point[0], y: point[1] };

http://jsfiddle.net/mdml/da37B/

于 2014-06-03T09:19:31.393 回答
8

正如上面chkaiserThe Composer所评论的那样,版本 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
    });

更多细节@ D3 v6 迁移指南

于 2020-12-06T18:20:47.610 回答
1

我怀疑你可能会尝试一些类似的东西:

var x = 0;

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

console.log(x);

除非你的手超级快,否则这将始终向控制台写入“0”,因为整个脚本会在你伸手去拿鼠标时执行。尝试将您的代码段直接放入控制台,移动鼠标,然后在控制台中键入“x”。您应该看到最新的 x 值。

我希望这会有所帮助,但我可能误解了这个问题。

于 2015-02-23T16:06:54.273 回答
0

我相信这是做同样事情的 V6 方式:

var svg = d3.select('body').append('svg')
    .attr('width', 600)
    .attr('height', 600)
    .on('mousemove', function(event) {
      let coords = d3.pointer(event);
      console.log( coords[0], coords[1] ) // log the mouse x,y position
    });

注意 - 这只是为了清楚起见 - 它已经在上面的评论中列出。

于 2021-06-16T09:59:40.993 回答