簡體   English   中英

D3 中的鼠標位置

[英]Mouse position in D3

我只想通過使用以下代碼使用 D3 獲取鼠標位置:

var x = 0;

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

x總是等於0 通過使用console.log() ,我可以看到x值在function()內部發生了變化,但是x的初始值是0

如何保存x值並稍后在我的應用程序中使用它?

你必須使用一個數組。 這將存儲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

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
    });

你可以通過這個例子很好地理解點擊和拖動功能。希望它會有所幫助。

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

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

正如上面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 遷移指南

我懷疑您可能正在嘗試以下操作:

var x = 0;

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

console.log(x);

除非您有超快的手,否則這將始終向控制台寫入“0”,因為在您伸手去拿鼠標時整個腳本都會執行。 嘗試將您的代碼片段直接放入控制台,移動鼠標,然后在控制台中鍵入“x”。 您應該會看到最新的 x 值。

我希望這會有所幫助,但我可能誤解了這個問題。

我相信這是 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
    });

注意 - 這只是為了清楚起見 - 它已經在上面的評論中列出。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM