Dev M
Dev M

Reputation: 1709

How to make the line follow the mouse on hover, but also have a circle follow the path with D3.js v6?

    const followPoints = React.useCallback(() => {
        const [x] = d3.mouse(anchorEl);
        const xDate = xScale.invert(x);
        const bisectDate = d3.bisector((d) => d.date).left;
        let baseXPos = 0;
    
        // draw circles on line
        d3.select(ref.current)
          .selectAll(".tooltipLinePoint")
          .attr("transform", (cur, i) => {
            const index = bisectDate(data[i].items, xDate, 1);
            const d0 = data[i].items[index - 1];
            const d1 = data[i].items[index];
            const d = xDate - d0?.date > d1?.date - xDate ? d1 : d0;
            if (d.date === undefined && d.value === undefined) {
              // move point out of container
              return "translate(-100,-100)";
            }
            const xPos = xScale(d.date);
            if (i === 0) {
              baseXPos = xPos;
            }
    
            let isVisible = true;
            if (xPos !== baseXPos) {
              isVisible = false;
            }
            const yPos = yScale(d.value);
    
            onChangePosition(d, i, isVisible);
    
            return isVisible
              ? `translate(${xPos}, ${yPos})`
              : "translate(-100,-100)";
          });
    
        drawLine(baseXPos);
        drawContent(baseXPos);
        drawBackground();
      }, [
        anchorEl,
        drawLine,
        drawContent,
        drawBackground,
        xScale,
        yScale,
        data,
        onChangePosition
      ]);
 
 


  [1]: https://codesandbox.io/s/d3react-multiline-chart-version-6-separate-components-tooltip-forked-ndf2j?file=/src/components/Tooltip.js:2736-4032

Upvotes: 0

Views: 203

Answers (1)

Michael Rovinsky
Michael Rovinsky

Reputation: 7230

In this code:

d3.select(anchorEl).on("mousemove.axisY", (event) => {
  [x] = d3.pointer(anchorEl); //.mouse()
});

replace d3.pointer(anchorEl) with [event.layerX];

It should work for D3 V6.

Upvotes: 1

Related Questions