-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.html
58 lines (52 loc) · 2.71 KB
/
main.html
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
<html>
<head>
<script src="https://cdn.socket.io/socket.io-1.3.5.js"></script>
<script>
socket = io(); // Initialize Socket.io
lines_to_draw = []; // Array of recieved lines to draw
line_coords = []; // Array of local lines to be sent
function startSavingLineCoords(e) {
ctx.lineTo((e.pageX - cvs.offsetLeft),(e.pageY - cvs.offsetTop)); // Draw line locally
ctx.stroke();
line_coords.push([(e.pageX - cvs.offsetLeft),(e.pageY - cvs.offsetTop)]); // Add coords to be sent
}
function onLoadCallback () {
cvs = document.getElementById('cvs');
ctx = cvs.getContext("2d");
mouseDown = false;
line_color = "#"+Math.random().toString(16).substring(2,8);
socket.on('s', function(line) {lines_to_draw.push(line);}); // Push recieved line in lines_to_draw
cvs.addEventListener("mousedown", function(e) {
mouseDown = true;
line_coords = [[(e.pageX - cvs.offsetLeft),(e.pageY - cvs.offsetTop)]]; // Starting coords for new line
ctx.strokeStyle = line_color;
ctx.beginPath(); // Start drawing locally
ctx.moveTo((e.pageX - cvs.offsetLeft),(e.pageY - cvs.offsetTop));
cvs.addEventListener("mousemove", startSavingLineCoords); // Start saving coords and drawing
});
cvs.addEventListener("mouseup", function(e) {
mouseDown = false;
cvs.removeEventListener("mousemove", startSavingLineCoords); // Stop saving local line coords
socket.emit('s', line_color+","+line_coords.join(',')); // send line
});
setInterval(function() { // Every 500 ms draw all lines in lines_to_draw
if (mouseDown) return; // wait for user to stop drawing line
while (lines_to_draw.length > 0) { // Draw all lines in lines_to_draw
var line_str = lines_to_draw.pop();
var new_line = line_str.split(','); // new_line is in format color,x1,y1,x2,y2,x3,y3...
ctx.strokeStyle = new_line[0]; // Color
ctx.beginPath();
ctx.moveTo(new_line[1], new_line[2]);
for (var i = 3;i < new_line.length;i+=2) {
ctx.lineTo(new_line[i], new_line[i+1]);
}
ctx.stroke();
}
}, 500);
}
</script>
</head>
<body onload="onLoadCallback()">
<canvas id="cvs" height="600" width="800" style="background:red;"> </canvas>
</body>
</html>