Chartjs-Horizontal line syncing across multiple charts when hovering with Chart.js in Typescript-react

0๐Ÿ‘

โœ…

I was able to solve this and even make it so it could apply to only certain charts on the page, and even have multiple different groups of synced up charts. The afterEvent sets the X value I want, and the className is set to tell which report group I would like to apply this hover to. If it detects it mousedOut, it sets the x value to 0 and therefore hides it. (Note that I ended up going with a vertical line instead of a horizontal, but the same thing could be done by flipping the x and y values and grabbing e.event.y).

const [xVal, setXVal] = useState(0)
const [currentClassName, setCurrentClassName] = useState('')
    
const verticalHover = {
    id:"verticalHover",
    afterEvent: (chart:any, e:any) => {
        if(e.event.type === 'mousemove') {
            setXVal(e.event.x)
            setCurrentClassName(chart.canvas.className)
        }
        else if(e.event.type === 'mouseout') {
            setXVal(0)
            setCurrentClassName(chart.canvas.className)
        }
    },
    afterDraw: (chartInstance: any) => {
        if(xVal !==0 && chartInstance.canvas.className ===currentClassName){
            const ctx = chartInstance.ctx;
                ctx.strokeStyle = "#6f6f6f";
                ctx.lineWidth = 2;
                ctx.beginPath();
                //Hardcoded yValues for now
                ctx.moveTo(xVal, 40);
                ctx.lineTo(xVal,265);
                ctx.stroke();
        }
    }
}

Chart.register(verticalHover);

Leave a comment