From 63d4e16fb87b702f4acca71b11cc105920833698 Mon Sep 17 00:00:00 2001 From: Robin Steinberg Date: Wed, 25 Aug 2021 22:57:21 +0200 Subject: [PATCH] Live preview - draw every coordinate --- index.html | 16 ++++--------- ts/app.ts | 68 ++++++++++++++++++++++++++++++++++++++++-------------- 2 files changed, 55 insertions(+), 29 deletions(-) diff --git a/index.html b/index.html index db244da..6de771c 100644 --- a/index.html +++ b/index.html @@ -9,18 +9,10 @@ - + \ No newline at end of file diff --git a/ts/app.ts b/ts/app.ts index b2c4951..427413c 100644 --- a/ts/app.ts +++ b/ts/app.ts @@ -4,6 +4,13 @@ class CanvasReceiverController { private ctx!: CanvasRenderingContext2D | null; private ws: WebSocket; + /** + * Represents whether the app is waiting for the first coordinates of a draw path. The first + * coordinates need to be handled with the moveTo canvas method instead of lineTo, therefore + * this variable is needed to decide how to handle the next coordinates. + */ + private waiting: boolean = false; + constructor() { this.canvasDiv = document.querySelector('#canvas') as HTMLDivElement; @@ -12,7 +19,7 @@ class CanvasReceiverController { this.ws = new WebSocket('ws://localhost:8081', 'json'); this.ws.onmessage = message => this.processMessage(message); - this.ws.onopen = () => this.ws.send("RECEIVER"); + this.ws.onopen = () => this.ws.send('RECEIVER'); } private createCanvas() { @@ -20,34 +27,61 @@ class CanvasReceiverController { 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) { - if (message.data === "CLEAR") { - this.canvasDiv.removeChild(this.canvas); - this.createCanvas(); + if (!this.canvas.getContext) { + alert('Canvas API unavailable, drawing will not work!'); } else { - this.draw(JSON.parse(message.data)); + this.ctx = this.canvas.getContext('2d'); } } - draw(path: Coordinates[]) { + processMessage(message: MessageEvent) { + switch (message.data) { + case 'CLEAR': + this.clear(); + break; + case 'START': + this.startDrawing(); + break; + case 'STOP': + this.stopDrawing(); + break; + default: + this.draw(JSON.parse(message.data)); + break; + } + } + + startDrawing() { + console.log('Received START command'); if (!this.ctx) { return; } - const first = path.shift(); + this.ctx.beginPath(); + this.waiting = true; + } - if (!first) { + stopDrawing() { + if (!this.ctx) { + return; + } + } + + private clear() { + this.canvasDiv.removeChild(this.canvas); + this.createCanvas(); + } + + draw(coordinates: Coordinates) { + if (!this.ctx) { return; } - this.ctx.beginPath(); - this.ctx.moveTo(first.x, first.y); - - for (const cur of path) { - this.ctx.lineTo(cur.x, cur.y); + if (this.waiting) { + this.waiting = false; + this.ctx.moveTo(coordinates.x, coordinates.y); + } else { + this.ctx.lineTo(coordinates.x, coordinates.y); } this.ctx.lineWidth = 1;