-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.html
76 lines (66 loc) · 2.31 KB
/
index.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Inscribed Square</title>
<script src="computation.js"></script>
</head>
<body>
<canvas id="canvas" width=2000px height=1000px style="background:white"></canvas>
<script>
var currentPath = [];
var lastP = null;
var isDrawing = false;
const canvas = document.getElementById('canvas');
canvas.style.cursor = "url('images/pencil.png') 0 32, auto";
const context = canvas.getContext('2d');
function drawLine(context, p1, p2, color = 'black') {
context.beginPath();
context.strokeStyle = color;
context.lineWidth = 1;
context.moveTo(p1.x, p1.y);
context.lineTo(p2.x, p2.y);
context.stroke();
context.closePath();
}
function updatePointAndDrawLine(e) {
var p1 = new Point(e.offsetX, e.offsetY);
drawLine(context, lastP, p1);
lastP = p1;
currentPath.push(lastP);
}
// Handle all canvas events
canvas.addEventListener('mousedown', e => {
lastP = new Point(e.offsetX, e.offsetY);
currentPath.push(lastP);
isDrawing = true;
});
canvas.addEventListener('mousemove', e => {
if (isDrawing === true) {
updatePointAndDrawLine(e);
}
});
window.addEventListener('mouseup', e => {
if (isDrawing === true) {
updatePointAndDrawLine(e);
isDrawing = false;
drawLine(context, currentPath[currentPath.length - 1], currentPath[0]);
var square = computeSquare(currentPath);
if (square == null) {
console.log("Square not found");
} else {
drawSquare(context, square);
}
currentPath = [];
}
});
function drawSquare(context, square) {
console.log("drawing square");
drawLine(context, square[0], square[1], 'red');
drawLine(context, square[1], square[2], 'red');
drawLine(context, square[2], square[3], 'red');
drawLine(context, square[3], square[0], 'red');
}
</script>
</body>
</html>