Skip to content

Instantly share code, notes, and snippets.

@jacobrossi
Last active October 30, 2021 13:30
Show Gist options
  • Save jacobrossi/a003bbc2987db506c5fc to your computer and use it in GitHub Desktop.
Save jacobrossi/a003bbc2987db506c5fc to your computer and use it in GitHub Desktop.
List of Touches - Pointer Events standard
//Code to create a list of touches called pointerList
var pointerList = []; //Array of all the pointers on the screen
window.addEventListener("pointerdown", updatePointer, true);
window.addEventListener("pointermove", updatePointer, true);
window.addEventListener("pointerup", remPointer, true);
window.addEventListener("pointercancel", remPointer, true);
function updatePointer(e) {
if(e.pointerType === "touch") {
pointerList[e.pointerId] = e; //Adds or update an entry to the array with the touch data for this touch
e.target.setPointerCapture(e.pointerId); //Captures all subsequent events for this touch to the canvas, so you still get the pointerup even if you lift outside of the canvas element's bounds
}
}
function remPointer(e) {
if(e.pointerType === "touch")
delete pointerList[e.pointerId]; //Removes the entry for this touch in the array now that it has lifted or been cancelled
}
//Example usage would be to poll the list in every browser render frame (~60FPS)
function sendTouchData() {
console.log(pointerList) //Replace this with your code to send the array back over WebSockets
requestAnimationFrame(sendTouchData); //Schedule another callback on the next render frame
}
requestAnimationFrame(sendTouchData); //Schedule the first callback for the next render frame
canvas {
touch-action: none; /* Disable default browser gestures and start getting pointer events for multi-touch */
}
@jacobrossi
Copy link
Author

Note: if you only need to support IE11+, you might consider replacing the array above with an ES6 Map, which will give you additional methods that make it easier to iterate the pointerList.

@jacobrossi
Copy link
Author

In sendTouchData(), the pointerList would be an array where each item represents a touch currently on the screen. In each item, you'll find raw data properties like:

pointerId - a unique identifier for the touch (similar to touch events' identifier property)
clientX - x coordinate of the finger relative to the window
clientY - y coordinate of the finger relative to the window
offsetX - x coordinate of the finger relative to the element touched
offsetY - y coordinate of the finger relative to the element touched
width - approximate width (px) of the finger on the screen
height - approximate height (px) of the finger on the screen

For more, see the standard: http://www.w3.org/TR/pointerevents/#pointerevent-interface

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment