var colors=["#FF0000","#00FF00","#0000FF"]; var colorId = [];
function handleStart(evt) { for(var i=0; i<evt.changedTouches.length;i++) { if (colors.length === 0) continue; var touch = evt.changedTouches[i]; colorId[touch.identifier] = colors.pop(); drawCircle(touch.pageX, touch.pageY, 20, colorId[touch.identifier],ctx); } }
function handleMove(evt) { for(var i=0;i<evt.changedTouches.length; i++){ var touch = evt.changedTouches[i]; if (colorId[touch.identifier] === undefined) continue; drawCircle(touch.pageX, touch.pageY, 20, colorId[touch.identifier], ctx); } }
function handleEnd(evt) { for (var i=0;i<evt.changedTouches.length; i++){ var touch = evt.changedTouches[i]; if (colorId[touch.identifier] === undefined) continue; colors.push(colorId[touch.identifier]); } }
function drawCircle(x, y, r, c, ctx) { ctx.beginPath(); ctx.arc(x, y, r, 0, 2 * Math.PI, true); ctx.fillStyle = c; ctx.fill(); ctx.stroke(); } </script> </body> </html>
What's left
There are lots of small topcs we haven't covered. In particular we have ignored the touchenter, touchleave and touchcancel events, but these are fairly easy to work with.
It is worth pointing out that there is additional information in the touch object that you can use to make your apps more sophisticated. For example, the radiusX, radiusY and rotationAngle can be used to fit an ellipse to the point of contact. The force property can also be used to work out how hard the user is pressing on the screen. Again, once you know they exist they are easy enough to use. The TouchList object also has the identifiedTouch method which can be used to return a touch object corresponding to a particular touch identifier.
Perhaps another article on touch is needed?
If you would like the code for this article register with I Programmer and visit the CodeBin.
Working with lower-level data is very much part of graphics. This extract from Ian Elliot's book on JavaScript Graphics looks at how to use typed arrays to access graphic data.
JavaScript should not be judged as if it was a poor version of the other popular languages - it isn't a Java or a C++ clone. It does things its own way. In particular, it doesn't do inheritance [ ... ]