Learn Create Your Own Split Screen

Next Page

Next we detect the end of the touch, determine the correct coordinates within the canvas, and calculate the difference (x-difference and y-difference) between the start and end of the touch.
function MyTouchEndHandler(MyEvent) { var rect = myCanvas.getBoundingClientRect(); // determine where our canvas is located var Touch_End_x = MyEvent.changedTouches[0].clientX - rect.left; // convert the first touch coordinates... var Touch_End_y = MyEvent.changedTouches[0].clientY - rect.top; // ...and store in variables var x_diff = Touch_End_x- Touch_Start_x; // calculate difference between start and end of touch var y_diff = Touch_End_y - Touch_Start_y; // also for y // // Do something useful with this information // We'll figure this out next // MyEvent.preventDefault() // don't let the browser also respond } addEventListener("touchend", MyTouchEndHandler); // call our handler when touches end
Pretty much, if the movement was to the left, it's a leftward swipe. We'd know that because the ending x-position would be less than the starting x-position, so when we subtract one from the other, we get a negative number.

In other words:

x_diff negative Swipe left detected
x_diff positive Swipe right detected
y_diff negative Swipe up detected
y_diff positive Swipe down detected