Add touch screen handling (#113)

* Add touch screen handling

* Feedback
This commit is contained in:
Will Scullin 2022-05-13 06:55:03 -07:00 committed by GitHub
parent 26796900a3
commit c648735b8a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 79 additions and 17 deletions

View File

@ -217,6 +217,8 @@ canvas {
image-rendering: optimizeSpeed;
width: 592px;
height: 416px;
touch-action: manipulation;
user-select: none;
}
#screen.mouseMode {

View File

@ -1,6 +1,9 @@
<!DOCTYPE html>
<head>
<title>PreApple II</title>
<meta name="viewport" content="width=640, user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes">
<link rel="stylesheet" type="text/css" href="css/apple2.css" />
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.2/css/all.css" />
</head>

View File

@ -1,10 +1,66 @@
import type Mouse from '../cards/mouse';
import { enableMouseMode } from './joystick';
type TouchEventWithTarget = TouchEvent & { target: HTMLCanvasElement };
export class MouseUI {
private mouse: Mouse;
constructor(private canvas: HTMLCanvasElement) {
const updateTouchXY = (event: TouchEventWithTarget) => {
const { targetTouches, target } = event;
if (targetTouches.length < 1) {
return;
}
const rect = target.getBoundingClientRect();
const leftPad = (rect.width - 560) / 2 + rect.left;
const topPad = (rect.height - 384) / 2 + rect.top;
const { clientX, clientY } = targetTouches[0];
const xPos = clientX - leftPad;
const yPos = clientY - topPad;
this.mouse.setMouseXY(
Math.max(Math.min(xPos, 559), 0),
Math.max(Math.min(yPos, 383), 0),
560,
384,
);
};
if ('ontouchstart' in window) {
this.canvas.addEventListener(
'touchmove',
(event: TouchEventWithTarget) => {
updateTouchXY(event);
}
);
this.canvas.addEventListener(
'touchstart',
(event: TouchEventWithTarget) => {
updateTouchXY(event);
// Make sure the mouse down is processed in a different
// pass as the move, so that a simple tap isn't treated like
// a drag.
setTimeout(() => this.mouse.setMouseDown(true), 100);
}
);
this.canvas.addEventListener(
'touchend',
(event: TouchEventWithTarget) => {
updateTouchXY(event);
this.mouse.setMouseDown(false);
}
);
this.canvas.addEventListener(
'touchcancel',
(event: TouchEventWithTarget) => {
updateTouchXY(event);
this.mouse.setMouseDown(false);
}
);
} else {
this.canvas.addEventListener(
'mousemove',
(event: MouseEvent & { target: HTMLCanvasElement} ) => {
@ -26,6 +82,7 @@ export class MouseUI {
this.mouse.setMouseDown(false);
});
}
}
setMouse = (mouse: Mouse) => {
this.mouse = mouse;