mousemove callback on a path element in d3js

2019-08-28 18:50发布

Link to example: http://bl.ocks.org/mbostock/1667367

I am trying to extend the following example, so that when i move my mouse over the graph and i registered a mousemove callback, i'll get the corresponding data to the cursor position. In a best case scenario, i would get the current price of Januar 2000 if i hovered my mouse over that location. I tried the following:

focus.append("path")
  .on('mousemove', function(d) {
      console.log(d);
  })
  .datum(data)
  .attr("clip-path", "url(#clip)")
  .attr("d", area);

But if i do that, all i get is the complete data every time the event is triggered. Is there functionality implemented in d3.js to achieve my goal, or do i have to work with the event coordinates manually ?

Thanks in advance :)

1条回答
Anthone
2楼-- · 2019-08-28 18:55

I think you might have to, but it isn't too hard with scales:

focus.append("path")
  .on('click', function(d) {
    console.log(event.offsetX - margin.left);
    var date = x.invert(event.offsetX - margin.left);
    console.log(date);

    var i = 0;
    while (d[i+1].date < date){
      i++;
    }
    console.log(d[i].date);
    console.log(d[i].price);
  })


1104.49 
893 
Sun Feb 28 2010 11:11:52 GMT-0600 (Central Standard Time) 
Mon Feb 01 2010 00:00:00 GMT-0600 (Central Standard Time) 
1104.49 

Alternatively, in addition to the area graph you could also plot markers showing month/price and add an onclick event to each of them.

There might be a better way of doing this; offsetX is is funky with firefox.

查看更多
登录 后发表回答