Last active
May 21, 2024 11:36
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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