-
Notifications
You must be signed in to change notification settings - Fork 0
/
canvas.html
55 lines (49 loc) · 1.27 KB
/
canvas.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
<!DOCTYPE html>
<html>
<head>
<style>
body { margin: 20px; }
canvas { border: 1px solid black; }
</style>
</head>
<body>
<canvas width="1100" height="850" id="canvas"></canvas>
<script>
let ws = new WebSocket('ws://localhost:9001/');
let send = (msg) => {
ws.send(JSON.stringify(msg));
};
let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');
let xy = (e) => {
let x = e.clientX - canvas.offsetLeft;
let y = e.clientY - canvas.offsetTop;
return [x, y];
};
let down = false;
canvas.addEventListener('mousemove', (e) => {
if (down) {
let [x, y] = xy(e);
ctx.lineTo(x, y);
ctx.stroke();
send({'type': 'move', 'x': x, 'y': y});
}
});
canvas.addEventListener('mousedown', (e) => {
down = true;
let [x, y] = xy(e);
ctx.beginPath();
ctx.strokeStyle = 'black';
ctx.lineWidth = 2;
ctx.moveTo(x, y);
send({'type': 'start', 'x': x, 'y': y});
});
canvas.addEventListener('mouseup', (e) => {
down = false;
let [x, y] = xy(e);
ctx.closePath();
send({'type': 'end', 'x': x, 'y': y});
});
</script>
</body>
</html>