guest_worker/www/index.html

124 lines
3.9 KiB
HTML
Raw Normal View History

2019-09-11 18:16:33 +02:00
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>MT Request: draw over the image</title>
<style media="screen">
svg{
height:600px;
width:600px;
border:solid 1px;
}
path {
fill: none;
stroke: red;
stroke-width: 2px;
}
</style>
</head>
<body>
<div id='interface'>
<img src="" id='sample'>
<svg id="canvas">
<path d="" id="stroke">
</svg>
<button id='submit'>Submit</button>
</div>
<script type="text/javascript">
let url = window.location.origin.replace('http', 'ws') +'/ws';
let svgEl = document.getElementById("canvas");
let strokeEl = document.getElementById('stroke');
let submitEl = document.getElementById('submit');
let strokes = [];
let isDrawing = false;
let draw = function(e) {
let pos = svgEl.getBoundingClientRect()
let x = e.x - pos['left'];
let y = e.y - pos['top'];
strokes.push([x, y, 0]);
let d = strokes2D(strokes);
console.log(d);
strokeEl.setAttribute('d', d);
socket.send(JSON.stringify({
'action': 'move',
'direction': [x, y]
}));
};
let penup = function(e) {
if(!isDrawing) {
return;
}
isDrawing = false;
document.body.removeEventListener('mousemove', draw);
if(strokes.length > 0){
// mark point as last of stroke
strokes[strokes.length - 1][2] = 1;
}
socket.send(JSON.stringify({
'action': 'up',
}));
};
let strokes2D = function(strokes) {
// strokes to a d attribute for a path
let d = "";
let last_stroke = undefined;
let cmd = "";
for (let stroke of strokes) {
if(!last_stroke) {
d += `M${stroke[0]},${stroke[1]} `;
cmd = 'M';
} else {
if (last_stroke[2] == 1) {
d += " m";
cmd = 'm';
} else if (cmd != 'l') {
d+=' l ';
cmd = 'l';
}
let rel_stroke = [stroke[0] - last_stroke[0], stroke[1] - last_stroke[1]];
d += `${rel_stroke[0]},${rel_stroke[1]} `;
}
last_stroke = stroke;
}
return d;
}
let socket = new WebSocket(url);
socket.addEventListener('message', function(e){
console.log('receive', e.data);
if(e.data == 'submitted') {
// TODO close the interface
}
});
document.body.addEventListener('mouseup', penup);
svgEl.addEventListener('mousedown', function(e){
isDrawing = true;
// start drawing
document.body.addEventListener('mousemove', draw);
});
submitEl.addEventListener('click', function(e){
if(!strokes.length){
alert('please draw before submitting');
return;
}
socket.send(JSON.stringify({
'action': 'submit'
}));
});
</script>
</body>
</html>