js.foresight
Version:
Predicts mouse trajectory to trigger actions as users approach elements, enabling anticipatory UI updates or pre-loading. Made with vanilla javascript and usable in every framework.
43 lines • 2.07 kB
JavaScript
/**
* Predicts the next mouse position based on a history of recent movements.
* It calculates velocity from the historical data and extrapolates a future point.
* The `history` array is mutated by this function: the new `currentPoint` is added,
* and if the history exceeds `positionHistorySize`, the oldest entry is removed.
*
* @param currentPoint - The current actual mouse coordinates.
* @param history - An array of previous mouse positions with timestamps.
* This array will be modified by this function.
* @param positionHistorySize - The maximum number of past positions to store and consider
* for the prediction.
* @param trajectoryPredictionTimeInMs - How far into the future (in milliseconds)
* to predict the mouse position.
* @returns The predicted {@link Point} (x, y coordinates). If history is insufficient
* (less than 2 points) or time delta is zero, returns the `currentPoint`.
*/
export function predictNextMousePosition(currentPoint, history, positionHistorySize, trajectoryPredictionTimeInMs) {
var now = performance.now();
var currentPosition = { point: currentPoint, time: now };
var x = currentPoint.x, y = currentPoint.y;
history.push(currentPosition);
if (history.length > positionHistorySize) {
history.shift();
}
if (history.length < 2) {
return { x: x, y: y };
}
var first = history[0];
var last = history[history.length - 1];
var dt = (last.time - first.time) / 1000;
if (dt === 0) {
return { x: x, y: y };
}
var dx = last.point.x - first.point.x;
var dy = last.point.y - first.point.y;
var vx = dx / dt;
var vy = dy / dt;
var trajectoryPredictionTimeInSeconds = trajectoryPredictionTimeInMs / 1000;
var predictedX = x + vx * trajectoryPredictionTimeInSeconds;
var predictedY = y + vy * trajectoryPredictionTimeInSeconds;
return { x: predictedX, y: predictedY };
}
//# sourceMappingURL=predictNextMousePosition.js.map