Created
July 2, 2012 12:49
-
-
Save viig99/3033111 to your computer and use it in GitHub Desktop.
Scrolling Direction.
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
/* This Function determines the direction of your displacement based upon the width and height of the widget / viewport width height you are scrolling them. | |
The theta is calculated based upon the width and height of the widget, and sets the direction based upon the 4 quadrants which are formed due to the intersection of lines drawn from the vertices and the point on origin on the center of the widget. | |
This Leads to a cleaner user experience for scrolling, as this works smoothly for small or large widgets. | |
@Arjun Variar | |
*/ | |
function returnDirectionOfScroll(deltaX,deltaY,width,height) { | |
var angle = Math.atan2(-deltaY,-deltaX).toDeg(); | |
var theta = Math.atan(height/width); | |
angle = angle > 360 ? (360 - angle) : angle; | |
if ( angle <= theta || angle > (360 - theta)) | |
return "left" | |
else if (angle <= (360 - theta) || angle > (180 + theta)) | |
return "down" | |
else if ( angle <= (180 + theta) || angle > (90 + theta)) | |
return "right" | |
else | |
return "up" | |
} | |
Number.prototype.toDeg = function() { | |
return (this * 180/Math.PI) >> 0; | |
} |
It would be down, left , left , left. Here the displacements are the difference between each touchmove cords or last touchmove and touchend, which would give the desired direction of movement.
the atan2 values are such ::
Math.atan2( ±0, -0 ) returns ±PI.
Math.atan2( ±0, +0 ) returns ±0.
Math.atan2( ±0, -x ) returns ±PI for x > 0.
Math.atan2( ±0, x ) returns ±0 for x > 0.
Math.atan2( -y, ±0 ) returns -PI/2 for y > 0.
Math.atan2( y, ±0 ) returns PI/2 for y > 0.
Math.atan2( ±y, -Infinity ) returns ±PI for finite y > 0.
Math.atan2( ±y, +Infinity ) returns ±0 for finite y > 0.
Math.atan2( ±Infinity, x ) returns ±PI/2 for finite x.
Math.atan2( ±Infinity, -Infinity ) returns ±3*PI/4.
Math.atan2( ±Infinity, +Infinity ) returns ±PI/4.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What will be the return value of each statement given below ?
returnDirectionOfScroll(0, -1, 10, 10);
returnDirectionOfScroll(0, 1, 10, 10);
returnDirectionOfScroll(-1, 0, 10, 10);
returnDirectionOfScroll(1, 0, 10, 10);