Skip to content

Instantly share code, notes, and snippets.

@fi-tomek-augustyn
Last active December 12, 2015 03:19
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fi-tomek-augustyn/4706155 to your computer and use it in GitHub Desktop.
Save fi-tomek-augustyn/4706155 to your computer and use it in GitHub Desktop.
Gesture detection: Implementing Swipe, Pinch/Stretch and Rotate gestures
// 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