d3.js

How to implement the feature on nivo line chart that snaps the tooltop to the nearest point on the chart?


I am trying to implement this feature from nivo linechart (https://nivo.rocks/line) where the tooltip always appears on the graph when my cursor in on it, and the tooltip always appears next to a point. Making the tooltip appear always and the transitions between tooltip positions is easy, but i dont understand how does it calculate which point is closest to my pointer, i have taken a look at the source code but i am somewhat at a loss here and i am drawing a complete blank, any help would be appreciated, if you could show some demo with source code that has this feature, than that would be a great help.


Solution

  • It uses d3-delaunay which computes a Voronoi diagram allowing to find the closest point.

    voronoi = d3.Delaunay
      .from(data, d => x(d.x), d => y(d.y))
      .voronoi([0, 0, width, height])
    

    You can find a showcase of this technique on the official Learn D3 documentation.