websocket-canvas/ts/canvasSender.ts

66 lines
2.1 KiB
TypeScript
Raw Normal View History

import CanvasUtil from "./canvas-util/canvasUtil.js";
import Coordinates from "./canvas-util/coordinates.js";
class CanvasSenderController {
private canvasUtil: CanvasUtil;
2021-08-24 17:21:14 +00:00
private canvasDiv: HTMLDivElement;
2021-08-24 20:26:23 +00:00
private ws: WebSocket;
2021-08-24 17:21:14 +00:00
private isMouseDown: boolean = false;
2021-08-24 17:57:25 +00:00
2021-08-24 17:21:14 +00:00
constructor() {
2021-08-24 20:26:23 +00:00
this.canvasDiv = document.querySelector('#canvas') as HTMLDivElement;
this.canvasUtil = new CanvasUtil(this.canvasDiv.offsetWidth, this.canvasDiv.offsetHeight);
2021-08-24 17:21:14 +00:00
const canvas = this.canvasUtil.getCanvas();
this.canvasDiv.appendChild(canvas);
2021-08-25 20:57:01 +00:00
if (!this.canvasUtil.isCanvasApiSupported) {
2021-08-25 20:57:01 +00:00
alert('Canvas API unavailable, drawing will not work!');
} else {
// Events
canvas.addEventListener('mousedown', e => this.onMouseDown(e));
canvas.addEventListener('mouseup', () => this.onMouseUp());
canvas.addEventListener('mousemove', e => this.onMouseMove(e));
canvas.addEventListener('touchstart', e => this.onMouseDown(e.touches[0]));
canvas.addEventListener('touchend', () => this.onMouseUp());
canvas.addEventListener('touchmove', e => this.onMouseMove(e.touches[0]));
2021-08-25 20:57:01 +00:00
}
2021-08-24 20:26:23 +00:00
this.ws = new WebSocket('ws://localhost:8081', 'json');
2021-08-25 20:57:01 +00:00
this.ws.onopen = () => this.ws.send('SENDER');
2021-08-24 17:21:14 +00:00
}
2021-08-25 20:57:01 +00:00
onMouseDown(event: MouseEvent | Touch) {
2021-08-24 17:21:14 +00:00
this.isMouseDown = true;
const coordinates = new Coordinates(event.clientX, event.clientY);
this.canvasUtil.startPath(coordinates);
this.ws.send('START');
this.ws.send(JSON.stringify(coordinates));
2021-08-24 17:21:14 +00:00
}
onMouseUp() {
this.isMouseDown = false;
this.canvasUtil.stopPath();
this.ws.send('STOP');
2021-08-24 17:21:14 +00:00
}
2021-08-25 20:57:01 +00:00
onMouseMove(event: MouseEvent | Touch) {
if (!this.isMouseDown) {
2021-08-24 17:21:14 +00:00
return;
}
2021-08-25 20:57:01 +00:00
const coordinates = new Coordinates(event.clientX, event.clientY);
this.canvasUtil.draw(coordinates);
2021-08-25 20:57:01 +00:00
this.ws.send(JSON.stringify(coordinates));
}
2021-08-24 17:21:14 +00:00
}
2021-08-24 17:57:25 +00:00
const app = new CanvasSenderController();
2021-08-24 17:21:14 +00:00
export { app };