Touch events for canvas drawing PhoneGap

StuartProgramming Blog

Touch events and mouse clicks are handled very differently between browsers and devices. I discovered this on a PhoneGap app when I wanted the user to be able to drag their finger and draw on the screen. X,Y coordinate seeking code I finally landed on below. Note that some devices, including my Nexus 10 with Paranoid return a touches collection off of the touchdown and touchmove events. This is not present on any of the other browsers or devices I tested.

function getCoordinateFromEventCrossBrowser(e, which) {
	var retval = 0;
	if (!e) var e = window.event;
	if (e.touches) {
		e = e.touches[0];
	}
	if (which.toUpperCase()=="X") {
		if (e.pageX) {
			retval = e.pageX;
		}
		else if (e.clientX) {
			retval = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
		}
	}
	else if (which.toUpperCase()=="Y") {
		if (e.pageY) {
			retval = e.pageY;
		}
		else if (e.clientY) {
			retval =  e.clientY + document.body.scrollLeft + document.documentElement.scrollLeft;
		}
	}
	return retval;
}
StuartTouch events for canvas drawing PhoneGap