Mouse position in D3

前端 未结 4 1727
别跟我提以往
别跟我提以往 2020-12-04 08:54

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];               


        
4条回答
  •  Happy的楠姐
    2020-12-04 09:10

    I suspect you might be trying some like:

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

    Unless you have super fast hands, this will always write "0" to the console because the whole script executes while you are reaching for the mouse. Try putting your snippet directly into the console, move the mouse around and then type "x" into the console. You should see the latest x value.

    I hope this helps, but I may have misunderstood the question.

提交回复
热议问题