This repository has been archived by the owner on May 30, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMousePosition.ts
90 lines (77 loc) · 2.56 KB
/
MousePosition.ts
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
interface IEventHandler {
handle(event: MouseEvent | TouchEvent): void;
}
class MouseEventHandler implements IEventHandler {
constructor(private mousePosition: MousePosition) {}
handle(event: MouseEvent | TouchEvent): void {
if (event instanceof MouseEvent) {
this.mousePosition.x = event.clientX;
this.mousePosition.y = event.clientY;
}
}
}
class TouchEventHandler implements IEventHandler {
constructor(private mousePosition: MousePosition) {}
handle(event: TouchEvent): void {
if (event.touches.length < 1) return;
this.mousePosition.x = event.touches[0].clientX;
this.mousePosition.y = event.touches[0].clientY;
}
}
abstract class MouseButtonHandler {
constructor(protected mousePosition: MousePosition) {}
abstract handle(event: MouseEvent): void;
}
class MouseDownHandler extends MouseButtonHandler {
handle(event: MouseEvent): void {
this.mousePosition.leftButtonHeld = true;
this.mousePosition.x = event.clientX;
this.mousePosition.y = event.clientY;
}
}
class MouseUpHandler extends MouseButtonHandler {
handle(event: MouseEvent): void {
this.mousePosition.leftButtonHeld = false;
this.mousePosition.x = event.clientX;
this.mousePosition.y = event.clientY;
}
}
class MousePosition {
x: number = 0;
y: number = 0;
leftButtonHeld: boolean = false;
private mouseEventHandler: IEventHandler;
private touchEventHandler: IEventHandler;
private mouseDownHandler: MouseButtonHandler;
private mouseUpHandler: MouseButtonHandler;
constructor(canvas: HTMLCanvasElement) {
this.mouseEventHandler = new MouseEventHandler(this);
this.touchEventHandler = new TouchEventHandler(this);
this.mouseDownHandler = new MouseDownHandler(this);
this.mouseUpHandler = new MouseUpHandler(this);
canvas.addEventListener("mousedown", (event) =>
this.mouseDownHandler.handle(event)
);
canvas.addEventListener("mouseup", (event) =>
this.mouseUpHandler.handle(event)
);
canvas.addEventListener("mousemove", (event) =>
this.mouseEventHandler.handle(event)
);
canvas.addEventListener("touchstart", (event) => {
this.leftButtonHeld = true;
this.touchEventHandler.handle(event);
});
canvas.addEventListener("touchcancel", () => {
this.leftButtonHeld = false;
});
canvas.addEventListener("touchend", (event) => {
this.leftButtonHeld = false;
this.touchEventHandler.handle(event);
});
canvas.addEventListener("touchmove", (event) =>
this.touchEventHandler.handle(event)
);
}
}
export default MousePosition;