Search code examples
javascriptchartscursorlineserieslightningchart

How can I move cursor over chart at any place and not just on the series data points?


I have 2 point line series each having default cursor on them. The default cursor runs along the series data (points). What I want is a cursor that I can move anywhere in the chart not just on the series data.


Solution

  • thanks for your question. Based on the tags, I'll assume you are using LightningChart JS.

    If I understood your desired behaviour correctly, you'd like the cursor to always be positioned at the users mouse, and displaying the solved closest data-point in the result table.

    This can be achieved with a Chart Marker, which is basically a cursor that can be created and positioned in application code.

    Custom cursor with ChartMarkerXY

    Here's a code snippet on how to:

    • listen to mouse events on the document.

    • solve nearest data-point from series.

    • position Chart Marker at arbitrary location.

    const marker = chart.addChartMarkerXY()
    
    document.addEventListener( 'mousemove', ( event ) => {
        // Solve nearest data point.
        const cursorPoint = chart.solveNearest( { x: event.clientX, y: event.clientY } )
        // Translate mouse location to Axis.
        const locationOnAxes = translatePoint(
            chart.engine.clientLocation2Engine( event.clientX, event.clientY ),
            chart.engine.scale,
            {
                x: chart.getDefaultAxisX().scale,
                y: chart.getDefaultAxisY().scale
            }
        )
        // Position Chart Marker, but override its location.
        marker
            .pointAt( cursorPoint )
            // Override Cursor location to that of mouse location.
            .setPosition( locationOnAxes )
    } )