1 var ongoingTouches = new Array;2 3 function colorForTouch(touch) {4 var id = touch.identifier;5 id = id.toString(16); // make it a hex digit6 return "#" + id + id + id;7 }8 9 function ongoingTouchIndexById(idToFind) {10 for (var i=0; i<ongoingTouches.length; i++) {11 var id = ongoingTouches[i].identifier;12 13 if (id == idToFind) {14 return i;15 }16 }17 return -1; // not found18 }19 20 function handleStart(evt) {21 evt.preventDefault();22 var el = document.getElementById("canvas");23 var ctx = el.getContext("2d");24 var touches = evt.changedTouches;25 26 for (var i=0; i<touches.length; i++) {27 ongoingTouches.push(touches[i]);28 var color = colorForTouch(touches[i]);29 ctx.fillStyle = color;30 ctx.fillRect(touches[i].pageX-2, touches[i].pageY-2, 4, 4);31 }32 }33 34 function handleMove(evt) {35 evt.preventDefault();36 var el = document.getElementById("canvas");37 var ctx = el.getContext("2d");38 var touches = evt.changedTouches;39 40 ctx.lineWidth = 4;41 42 for (var i=0; i<touches.length; i++) {43 var color = colorForTouch(touches[i]);44 var idx = ongoingTouchIndexById(touches[i].identifier);45 46 ctx.fillStyle = color;47 ctx.beginPath();48 ctx.moveTo(ongoingTouches[idx].pageX, ongoingTouches[idx].pageY);49 ctx.lineTo(touches[i].pageX, touches[i].pageY);50 ctx.closePath();51 ctx.stroke();52 ongoingTouches.splice(idx, 1, touches[i]); // swap in the new touch record53 }54 }55 56 function handleEnd(evt) {57 evt.preventDefault();58 var el = document.getElementById("canvas");59 var ctx = el.getContext("2d");60 var touches = evt.changedTouches;61 62 ctx.lineWidth = 4;63 64 for (var i=0; i<touches.length; i++) {65 var color = colorForTouch(touches[i]);66 var idx = ongoingTouchIndexById(touches[i].identifier);67 68 ctx.fillStyle = color;69 ctx.beginPath();70 ctx.moveTo(ongoingTouches[i].pageX, ongoingTouches[i].pageY);71 ctx.lineTo(touches[i].pageX, touches[i].pageY);72 ongoingTouches.splice(i, 1); // remove it; we're done73 }74 }75 76 function handleCancel(evt) {77 evt.preventDefault();78 var touches = evt.changedTouches;79 80 for (var i=0; i<touches.length; i++) {81 ongoingTouches.splice(i, 1); // remove it; we're done82 }83 }84 85 86 function startup() {87 var el = document.getElementById("canvas");88 el.addEventListener("touchstart", handleStart, false);89 el.addEventListener("touchend", handleEnd, false);90 el.addEventListener("touchcancel", handleCancel, false);91 el.addEventListener("touchleave", handleEnd, false);92 el.addEventListener("touchmove", handleMove, false);93 }94 95 96 window.addEventListener('load', function(e){97 startup();98 }, true);
Enlace
El enlace para compartir es: