Skip to content

Instantly share code, notes, and snippets.

@Ctrlmonster
Last active May 21, 2024 11:36
Show Gist options
  • Save Ctrlmonster/6afdd7505ff97838796b5b859cecaf16 to your computer and use it in GitHub Desktop.
Save Ctrlmonster/6afdd7505ff97838796b5b859cecaf16 to your computer and use it in GitHub Desktop.
Get the pointer position with the smallest amount of input lag using `getCoalescedEvents` and `getPredictedEvents`. This is useful when syncing elements to cursor position (i.e. in a drag event)
const getPointerPosition = (() => {
const testEvent = new PointerEvent("pointermove");
// check for the existence of getCoalescedEvents and getPredictedEvents (Safari currently has both in tech preview)
const _pos = {x: 0, y: 0};
if (testEvent.getCoalescedEvents && testEvent.getCoalescedEvents) {
return (evt: PointerEvent, pos: {x: number, y: number} = _pos) => {
evt.stopPropagation();
// using the first prediction (the latest seems too chaotic when the cursor comes to a halt)
const latestPrediction = evt.getPredictedEvents().shift();
if (latestPrediction) {
pos.x = latestPrediction.clientX;
pos.y = latestPrediction.clientY;
return pos;
} else {
// use the latest raw pointer data
const fasterEvt = evt.getCoalescedEvents().pop()!;
pos.x = fasterEvt.clientX;
pos.y = fasterEvt.clientY;
return pos;
}
}
}
if (testEvent.getCoalescedEvents) {
return (evt: PointerEvent, pos: {x: number, y: number} = _pos) => {
evt.stopPropagation();
const fasterEvt = evt.getCoalescedEvents().pop()!;
pos.x = fasterEvt.clientX;
pos.y = fasterEvt.clientY;
return pos;
}
}
return (evt: PointerEvent, pos: {x: number, y: number} = _pos) => {
evt.stopPropagation();
pos.x = evt.clientX;
pos.y = evt.clientY;
return pos;
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment