Last active
December 12, 2015 03:19
-
-
Save fi-tomek-augustyn/4706155 to your computer and use it in GitHub Desktop.
Gesture detection: Implementing Swipe, Pinch/Stretch and Rotate gestures
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
// Define constant values | |
var MIN_ROTATION = 20; | |
var MIN_SCALE = .3; | |
var MIN_SWIPE_DISTANCE = 50; | |
// Define variables | |
var rotation, scale, recognized, translationX, translationY; | |
/** | |
* Reset gesture | |
*/ | |
function resetGesture(event) { | |
rotation = 0; | |
scale = 1; | |
translationX = translationY = 0; | |
recognized = false; | |
} | |
/** | |
* Detect gesture | |
*/ | |
function detectGesture(event) { | |
// Disable built-in inertia | |
if (event.detail == event.MSGESTURE_FLAG_INERTIA) { | |
return; | |
} | |
// Update total values | |
rotation += event.rotation * 180 / Math.PI; | |
scale *= event.scale; | |
translationX += event.translationX; | |
translationY += event.translationY; | |
// Try to detect a gesture when not recognized | |
if (!recognized) { | |
// Gesture direction | |
var direction; | |
// Check for horizontal swipe | |
if (Math.abs(translationX) > MIN_SWIPE_DISTANCE) { | |
recognized = true; | |
// Check direction | |
direction = translationX < 0 ? 'left' : 'right'; | |
console.log('Horizontal swipe: ', direction); | |
// Check for vertical swipe | |
} else if (Math.abs(translationY) > MIN_SWIPE_DISTANCE) { | |
recognized = true; | |
// Check direction | |
direction = translationY < 0 ? 'up' : 'down' | |
console.log('Vertical swipe: ', direction); | |
} | |
// Check for rotation | |
if (Math.abs(rotation) >= MIN_ROTATION) { | |
recognized = true; | |
console.log('Rotate: ', rotation < 0 ? 'left' : 'right'); | |
// Check for Pinch/Stretch | |
} else if (Math.abs(scale - 1) > MIN_SCALE) { | |
recognized = true; | |
console.log('Scale: ', scale > 1 ? 'stretch' : 'pinch'); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment