Mouse position in D3

前端 未结 4 1724
别跟我提以往
别跟我提以往 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条回答
  • 2020-12-04 09:01

    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
    
    0 讨论(0)
  • 2020-12-04 09:04

    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
        });
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-04 09:24

    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/

    0 讨论(0)
提交回复
热议问题