-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
85 lines (73 loc) · 2.06 KB
/
index.html
File metadata and controls
85 lines (73 loc) · 2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<html>
<canvas id="canvas" height="720" width="1280"></canvas>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var opts = {};
opts['sync disconnect on unload'] = true;
var socket = io.connect(window.location.hostname, opts);
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
// add border to canvas
$(canvas).css({'border':'1px solid black'});
// init
var rectangles = {},
myId, cx, cy,
tile_size = 10,
name;
// handle arrow key presses
$(document).bind("keydown", function (e) {
switch(e.keyCode)
{
//left
case 37:
cx = (cx - tile_size < 0) ? canvas.width : cx - tile_size;
break;
//up
case 38:
cy = (cy - tile_size < 0) ? canvas.height : cy - tile_size;
break;
//right
case 39:
cx = (cx + tile_size > canvas.width) ? 0 : cx + tile_size;
break;
//down
case 40:
cy = (cy + tile_size > canvas.height) ? 0 : cy + tile_size;
break;
}
// draw and tell the server we've moved
draw(cx, cy);
socket.emit('move', { 'id': myId, 'loc': { 'x': cx, 'y': cy } });
});
function draw (x, y) {
// clear the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// draw others
for (var i in rectangles) {
console.log(i);
if (rectangles.hasOwnProperty(i) && rectangles[i].id != myId) {
ctx.fillStyle = "black";
ctx.fillRect(rectangles[i].loc.x, rectangles[i].loc.y, tile_size, tile_size);
}
}
// draw me
ctx.fillStyle = "black";
ctx.fillText(name, x - 2, y - 3);
ctx.fillStyle = "red";
ctx.fillRect(x, y, tile_size, tile_size);
}
socket.on('update', function (data) {
rectangles = data;
draw(cx, cy);
});
socket.on('init', function (data) {
myId = data.newRect.id;
cx = data.newRect.loc.x;
cy = data.newRect.loc.y;
rectangles = data.rectangles;
name = data.newRect.name;
draw(cx, cy);
});
</script>
</html>