CxJS

SnapPointFinder

import { SnapPointFinder } from 'cx/charts'; Copied

SnapPointFinder locates the nearest data point to the cursor position and outputs its coordinates. Use it to snap markers, display tooltips at data points, or highlight specific values on a graph.

<div controller={PageController}>
  <Svg style="width: 100%; height: 300px">
    <Chart
      margin="30 30 40 50"
      axes={{
        x: { type: NumericAxis },
        y: { type: NumericAxis, vertical: true },
      }}
    >
      <MouseTracker x={m.cursor.x} y={m.cursor.y}>
        <Gridlines />
        <SnapPointFinder
          cursorX={m.cursor.x}
          snapX={m.snapX}
          snapY={m.snapY}
          maxDistance={Infinity}
        >
          <LineGraph data={m.data} colorIndex={0} />
        </SnapPointFinder>
        <MarkerLine visible={hasValue(m.snapX)} x={m.snapX} colorIndex={8} />
        <Marker
          visible={hasValue(m.snapX)}
          x={m.snapX}
          y={m.snapY}
          colorIndex={0}
          size={10}
          tooltip={{
            alwaysVisible: true,
            text: { tpl: "({snapX:n;0}, {snapY:n;1})" },
            placement: "up",
            destroyDelay: 0,
            createDelay: 0,
          }}
        />
      </MouseTracker>
    </Chart>
  </Svg>
  <div style="display: flex; justify-content: space-between; align-items: center; margin-top: 8px">
    <Button onClick="generate">Generate</Button>
    <span style="color: #666">Move mouse to snap to nearest data point</span>
  </div>
</div>
Move mouse to snap to nearest data point

How It Works

  1. Wrap graph elements (LineGraph, ColumnGraph, etc.) inside SnapPointFinder
  2. Pass the cursor position via cursorX (and optionally cursorY)
  3. Bind snapX/snapY to receive the coordinates of the nearest point
  4. Use the snapped coordinates with Marker, MarkerLine, or tooltip elements

See Also

Configuration

PropertyTypeDefaultDescription
cursorXnumberCursor X position (from MouseTracker).
cursorYnumberCursor Y position (from MouseTracker).
snapXnumberBind for X coordinate of the nearest point.
snapYnumberBind for Y coordinate of the nearest point.
snapRecordobjectBind for full data record of the nearest point.
maxDistancenumber50Maximum snap distance. Set to Infinity for TimeAxis or sparse data.
convertXfunctionConvert X values (e.g., dates) to numbers. Required for TimeAxis.
convertYfunctionConvert Y values (e.g., dates) to numbers. Required for TimeAxis.