Created
May 1, 2019 09:34
-
-
Save dp21g/2d19799f132477fda3adf9f92fa799ac to your computer and use it in GitHub Desktop.
Track pinch gestures in browser using only touch events (attempt to not use HammerJS)
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
// 1. Track the touches | |
let touches = { | |
start: [], | |
end: [], | |
}; | |
// 2. When the touch events end, calculate if its pinching inwards or outwards | |
const handleTouchEnd = () => { | |
if (touches.start.length === 0 || touches.end.length === 0) { | |
return; | |
} | |
const start = touches.start; | |
const end = touches.end; | |
// the order of the array doesn't dicatate which touch was the left most or right most. | |
const rightTouchedBeforeLeft = start[0].clientX > start[1].clientX ? 1 : 0; | |
const leftTouch = start[0 + rightTouchedBeforeLeft].clientX - end[0 + rightTouchedBeforeLeft].clientX; | |
const rightTouch = start[1 - rightTouchedBeforeLeft].clientX - end[1 - rightTouchedBeforeLeft].clientX; | |
const min = Math.min(start[0].clientX, start[1].clientX); | |
const max = min === start[0].clientX ? start[1].clientX : start[0].clientX; | |
const targetPx = ((max - min) / 2) + min; | |
if ((leftTouch > 0 && rightTouch < 0)) { | |
console.log(`pinching outwards, selected pixel is ${targetPx}`); | |
} else if (leftTouch < 0 && rightTouch > 0) { | |
console.log(`pinching inwards, selected pixel is ${targetPx}`); | |
} | |
touches.start = []; | |
touches.end = []; | |
} | |
// 3. Add the first movement as the start. | |
// This is because I've found that onTouchStart doesn't always pick up the two touches | |
const handleTouchMove = (e) => { | |
if (e.touches.length === 2) { | |
if (touches.start.length === 0) { | |
touches.start = e.touches; | |
} else { | |
touches.end = e.touches; | |
} | |
} | |
} | |
// 4. Add the touch events to a element | |
<div onTouchMove={handleTouchMove} onTouchEnd={handleTouchEnd} /> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment