forked from jakesgordon/javascript-racer
-
Notifications
You must be signed in to change notification settings - Fork 11
/
touch.js
99 lines (80 loc) · 2.18 KB
/
touch.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
var ongoingTouches = [];
function copyTouch({ identifier, pageX, pageY }) {
return { identifier, pageX, pageY };
}
function ongoingTouchIndexById ( idToFind ) {
for (var i = 0; i < ongoingTouches.length; i++) {
var id = ongoingTouches[i].identifier;
if ( id == idToFind ) { return i; }
}
return -1; // not found
}
class TouchControl
{
constructor(canvasTarget) // e.g. canvasTarget = document.getElementById("canvas")
{
this.target = canvasTarget;
canvasTarget.addEventListener("touchstart", this.handleStart, false);
canvasTarget.addEventListener("touchend", this.handleEnd, false);
canvasTarget.addEventListener("touchcancel", this.handleCancel, false);
canvasTarget.addEventListener("touchmove", this.handleMove, false);
}
update ()
{
console.log("touch update called");
}
handleStart(e)
{
e.preventDefault();
var touches = e.changedTouches;
for (var i = 0; i < touches.length; i++)
{
ongoingTouches.push(copyTouch(touches[i]));
}
} // end handle touch-start
handleMove(e)
{
e.preventDefault();
var touches = e.changedTouches;
for (var i = 0; i < touches.length; i++)
{
var idx = ongoingTouchIndexById(touches[i].identifier);
if (idx >= 0)
{
ongoingTouches.splice(idx, 1, copyTouch(touches[i])); // swap in the new touch record
}
else
{
console.log("can't figure out which touch to continue");
}
}
} // end handle touch-move
handleEnd(e)
{
e.preventDefault();
var touches = e.changedTouches;
for (var i = 0; i < touches.length; i++)
{
//console.log ( "ended touch: (" + touches[i].pageX + ", " + touches[i].pageY + ") " );
var idx = ongoingTouchIndexById(touches[i].identifier);
if (idx >= 0)
{
ongoingTouches.splice(idx, 1); // remove it; we're done
}
else
{
console.log("can't figure out which touch to end");
}
}
} // end handle touch-end
handleCancel(e)
{
e.preventDefault();
var touches = e.changedTouches;
for (var i = 0; i < touches.length; i++)
{
var idx = ongoingTouchIndexById(touches[i].identifier);
ongoingTouches.splice(idx, 1); // remove it; we're done
}
} // end handle touch-cancel
} // end of touchDetector class