ChartJS - Use dispatchEvent to invoke multiple line charts tooltips but not worked with large width

Viewed 36

I had multiple Line Charts in a React project and wanted to have a common vertical Crosshairs and display tooltip in the corresponding position. because the actual situation was more complex, I simplified this part and built a demo.

There is NO Crosshair in the demo, but essentially a transparent Div that covers all the charts is placed at the top level and all the onMouseMove, onMouseLeave and onMouseEnter methods are passed to the parent component.

Here are some of the core code:

 onMouseMove={(event) => {
          handleMoveEventWithAllCanvas(event);
          setCrosshairXIndex(event.nativeEvent.offsetX);
 }}
function handleMoveEventWithAllCanvas(event) {
    refCanvases.current.forEach((canvas,i) => {
      // Get the point where the mouse is
      let rect = canvas.current.getBoundingClientRect();

      let newEvent = new MouseEvent(event.type, {
        clientX: rect.left + event.nativeEvent.offsetX,
        clientY: rect.top + height/2,
      })
      canvas.current.dispatchEvent(newEvent);
    })
  }

This method worked well when this chart was relatively small (not quite sure of the exact numbers)! But when the chart is wider, the tooltip will not be triggered on the right side of the chart. I used afterEventhook to check what events the chart was receiving, and I found that y and/or x could become negative numbers.

This is the log output from the console:

// Tooltips worked 
newEvent clientX: 1630 clientY: 345
customEventListener: evt.type: mousemove
customEventListener: clientX: 1630 offsetX: 0 pageX: 1630 X: 407
customEventListener: clientY: 345 offsetY: -49 pageY: 345 Y: 49


// Tooltips stuck from this event
newEvent clientX: 1631 clientY: 345
customEventListener: evt.type: mousemove
customEventListener: clientX: 1631 offsetX: 1 pageX: 1631 X:1
customEventListener: clientY: 345 offsetY: -49 pageY: 345 Y: -49

I've been stuck in this problem for a long time, my Chart is set up in responsive mode according to this document, and I've checked the source code of Chartjs for event handling, but I couldn't find the answer

Thanks!

0 Answers
Related