72 lines
1.7 KiB
TypeScript
72 lines
1.7 KiB
TypeScript
|
class CanvasReceiverController {
|
||
|
private canvasDiv: HTMLDivElement;
|
||
|
private canvas!: HTMLCanvasElement;
|
||
|
private ctx!: CanvasRenderingContext2D | null;
|
||
|
private ws: WebSocket;
|
||
|
|
||
|
constructor() {
|
||
|
this.canvasDiv = document.querySelector('#canvas') as HTMLDivElement;
|
||
|
|
||
|
this.createCanvas();
|
||
|
|
||
|
this.ws = new WebSocket('ws://localhost:8081', 'json');
|
||
|
|
||
|
this.ws.onmessage = message => this.processMessage(message);
|
||
|
this.ws.onopen = () => this.ws.send("RECEIVER");
|
||
|
}
|
||
|
|
||
|
private createCanvas() {
|
||
|
this.canvas = document.createElement('canvas');
|
||
|
this.canvasDiv.appendChild(this.canvas);
|
||
|
this.canvas.width = this.canvas.offsetWidth;
|
||
|
this.canvas.height = this.canvas.offsetHeight;
|
||
|
this.ctx = this.canvas.getContext('2d');
|
||
|
}
|
||
|
|
||
|
processMessage(message: MessageEvent<any>) {
|
||
|
if (message.data === "CLEAR") {
|
||
|
this.canvasDiv.removeChild(this.canvas);
|
||
|
this.createCanvas();
|
||
|
} else {
|
||
|
this.draw(JSON.parse(message.data));
|
||
|
}
|
||
|
}
|
||
|
|
||
|
draw(path: Coordinates[]) {
|
||
|
if (!this.ctx) {
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
const first = path.shift();
|
||
|
|
||
|
if (!first) {
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
this.ctx.beginPath();
|
||
|
this.ctx.moveTo(first.x, first.y);
|
||
|
|
||
|
for (const cur of path) {
|
||
|
this.ctx.lineTo(cur.x, cur.y);
|
||
|
}
|
||
|
|
||
|
this.ctx.lineWidth = 1;
|
||
|
this.ctx.stroke();
|
||
|
}
|
||
|
}
|
||
|
|
||
|
|
||
|
class Coordinates {
|
||
|
public x: number;
|
||
|
public y: number;
|
||
|
|
||
|
constructor(x: number, y: number) {
|
||
|
this.x = x;
|
||
|
this.y = y;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
const app = new CanvasReceiverController();
|
||
|
|
||
|
export { app };
|