-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
96 lines (77 loc) · 2.19 KB
/
main.js
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
86
87
88
89
90
91
92
93
94
95
96
// logical (stored) canvas size
const CANVAS_WIDTH = 1600;
const CANVAS_HEIGHT = 1600;
const PEN_WIDTH = 3; // logical pen width
const PEN_COLOR = '#404040';
// const DRAW_HOST = location.hostname;
const DRAW_HOST = 'draw.chev.me';
const DRAW_PORT = 43471;
var body = document.querySelector('body');
var draw = false;
var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');
var dpr = window.devicePixelRatio || 1;
// setup canvas
canvas.style.width = CANVAS_WIDTH + 'px';
canvas.style.height = CANVAS_HEIGHT + 'px';
canvas.width = CANVAS_WIDTH * dpr;
canvas.height = CANVAS_HEIGHT * dpr;
// setup context
ctx.scale(dpr, dpr);
ctx.lineWidth = PEN_WIDTH;
ctx.lineCap = "round";
ctx.lineJoin = "round";
ctx.strokeStyle = PEN_COLOR;
var ws = new ReconnectingWebSocket('ws://' + DRAW_HOST + ':' + DRAW_PORT);
var points = [];
function sendPath() {
if (points.length == 0) {
return;
}
var path = { points: points };
ws.send(JSON.stringify(path));
points = [];
}
ws.onmessage = function(msg) {
console.log('recv', msg);
// draw paths
var j = 0;
paths = JSON.parse(msg.data);
for (var path of paths) {
// ctx.fillText(path.ip + ':' + path.port, path.points[0][0], path.points[0][1]);
ctx.moveTo(path.points[0][0], path.points[0][1]); // first point
for (var i = 1; i < path.points.length; i++) {
// rest points
ctx.lineTo(path.points[i][0], path.points[i][1]);
}
ctx.stroke();
}
console.log('%s points total', j);
}
canvas.addEventListener('mousedown', function(e) {
if (e.button !== 0) return; // not left key
body.classList.add('drawing');
draw = true;
var mouseX = e.pageX - this.offsetLeft;
var mouseY = e.pageY - this.offsetTop;
ctx.moveTo(mouseX, mouseY);
points.push([mouseX, mouseY]);
});
canvas.addEventListener('mouseup', function(e) {
body.classList.remove('drawing');
draw = false;
sendPath();
});
canvas.addEventListener('mouseleave', function(e) {
body.classList.remove('drawing');
draw = false;
sendPath();
});
canvas.addEventListener('mousemove', function(e) {
if (!draw) return;
var mouseX = e.pageX - this.offsetLeft;
var mouseY = e.pageY - this.offsetTop;
ctx.lineTo(mouseX, mouseY);
ctx.stroke();
points.push([mouseX, mouseY]);
});