Learn Create Your Own Split Screen

Next Page

Recall that touch coordinates are given relative to the upper-left corner of the browser window, but we need them relative to our canvas.

If you skipped over this material before, you really need to go back and do it now.

To make the adjustments, we find where our canvas is located, relative to the corner of the browser. We don't have to do this inside the for-loop, since the canvas doesn't move and answer would be the same for each finger.

Then, inside the loop, we do a simple subtraction to get the finger coordinates (x and y) relative to the corner of the canvas. We have to do it inside the loop, since each finger is in a different place.

function MyTouchHandler (MyEvent) { var rect = myCanvas.getBoundingClientRect(); for (var i=0; i < MyEvent.touches.length; i++) { var x = MyEvent.touches[i].clientX - rect.left; var y = MyEvent.touches[i].clientY - rect.top; } MyEvent.preventDefault() }