blob: 0806e16688e7754d121dc916bfe680b4bf40b566 [file] [log] [blame]
Alex Perry554cec02019-03-23 20:15:12 -07001import {FT_TO_M, FIELD_WIDTH} from './constants';
2import {drawField} from './field';
3import {drawRobot} from './robot';
4
5const FIELD_WIDTH = 27 * FT_TO_M;
6
7function main(): void {
8 const vis = new Visualiser();
9}
10
11class Visualiser {
12 private x = 3;
13 private y = 0;
14 private theta = 0;
15
16 constructor() {
17 const canvas = <HTMLCanvasElement>document.getElementById('field');
18 const ctx = canvas.getContext('2d');
19
20 const server = location.host;
21 const socket = new WebSocket(`ws://${server}/ws`);
22 const reader = new FileReader();
23 reader.addEventListener('loadend', (e) => {
24 const text = e.srcElement.result;
25 const j = JSON.parse(text);
26 this.x = j.robot.x;
27 this.y = j.robot.y;
28 this.theta = j.robot.theta;
29 });
30 socket.addEventListener('message', (event) => {
31 reader.readAsText(event.data);
32 });
33 window.requestAnimationFrame(() => this.draw(ctx));
34 }
35
36 reset(ctx : CanvasRenderingContext2D) : void {
37 ctx.setTransform(1,0,0,1,0,0);
38 const size = Math.min(window.innerHeight, window.innerWidth) * 0.98;
39 ctx.canvas.height = size;
40 ctx.canvas.width = size;
41 ctx.clearRect(0,0,size,size);
42
43 ctx.translate(size/2, size);
44 ctx.rotate(-Math.PI / 2);
45 ctx.scale(1, -1);
46 const M_TO_PX = size / FIELD_WIDTH
47 ctx.scale(M_TO_PX, M_TO_PX);
48 ctx.lineWidth = 1 / M_TO_PX;
49
50 ctx.beginPath();
51 }
52
53 draw(ctx : CanvasRenderingContext2D) : void {
54 this.reset(ctx);
55
56 drawField(ctx);
57 drawRobot(ctx, this.x, this.y, this.theta);
58 window.requestAnimationFrame(() => this.draw(ctx));
59 }
60}
61
62main();