|Creating Web Apps - The Touch API|
|Written by Mike James|
Page 3 of 4
Point Contact ID and touchend
OK, so now you can track points of contact let's try a slightly more ambitious idea. Color the first trail red, the next green and the third and subsequent trails blue.
This is surprisingly easy:
Then you will notice that there are some interesting problems. The first is that if you start drawing two trails - the first red the second green - and take your first finger off the screen you will discover that the green trail turns red. This might be what you want but keeping colors fixed is a more useful alternative. Another problem is that if you try to keep one finger fixed and move the second you will see the red circles in among the green.
The point is that the first finger doesn't always turn up as the first touch object in the list.
The solution to this problem is that the the touch object includes an id for each point of contact so that you can track a particular finger. Actually using the id can be quite messy so let's look at an example.
First we need to set up a pool of possible colors that we can use:
and an array that stores which color goes with which touch id:
Both of these are global variables.
Next we need to modify the touchstart event handler to assign a color to each point of contact based on the touch id:
The touchmove event handler just need one small change to make it use the assigned color:
Again the if statement stops us from using more colors than were originally assigned - if a color hasn't been assigned to a touch then don't draw it.
At this point it is obvious that we need to write a touchend event handler. If we don't the colors that are popped off the color pool never get returned to the color pool and we eventually run out of colors.
The touchend event works in exactly the same way as the other two so there isn't much point in going in for a detailed explanation. All we need is to add the event handler:
and define it:
All the event handler does is return the color to the color pool using the push operation. Again the if statement save us from pushing an unassigned color back into the color pool.
Notice that as the colors are removed using pop and put back using push and the order that the points of contact come to an end isn't always the same the colors change their order as you use them.
|Last Updated ( Monday, 21 January 2013 )|