-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
725 lines (646 loc) · 25.9 KB
/
index.html
File metadata and controls
725 lines (646 loc) · 25.9 KB
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Shape Drawing Tool</title>
<style>
body {
display: flex;
flex-direction: column;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f0f0f0;
}
canvas {
border: 1px solid black;
}
.distanceLabel {
position: absolute;
background-color: transparent;
padding: 2px 5px;
font-size: 16px;
transform: translate(-50%, 0%);
color: blue;
}
.angleLabel {
position: absolute;
background-color: transparent;
padding: 2px 5px;
font-size: 16px;
transform: translate(-50%, 0%);
color: green;
}
.button-container {
margin-bottom: 10px;
}
.button-container button {
margin: 0 5px;
}
#message {
background-color: rgba(255, 255, 255, 0.8);
padding: 5px 10px;
border: 1px solid #000;
font-size: 18px;
}
.bold {
font-weight: bold;
text-decoration: underline;
}
.highlight {
color: red;
}
footer {
margin-top: auto;
padding: 10px;
text-align: center;
width: 100%;
}
</style>
</head>
<body>
<h1>Shape Drawing Tool</h1>
<p>
This is a simple web-based tool that allows users to draw shapes by
dragging on a canvas.
</p>
<div class="button-container">
<button id="resetCanvas">Reset Canvas</button>
<button id="undoAction">Undo</button>
</div>
<div>
<div id="message">
To draw a line segment, start dragging from point A to Point B.
</div>
</div>
<canvas id="myCanvas" width="800" height="600"></canvas>
<footer
style="margin-top: auto; padding: 10px; text-align: center; width: 100%"
>
Made By <a href="https://pranjalgoyal.dev">Pranjal Goyal</a>.
</footer>
<script>
window.onload = function () {
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
const segments = []; // Array to hold line segments
const points = []; // Array to hold points
const distanceLabels = []; // Array to hold distance labels
const angleLabels = []; // Array to hold angle labels
let startPoint = null;
let isDragging = false;
let isPointDragging = false;
let draggedPoint = null;
const SNAP_DISTANCE = 15; // Distance to snap to existing points
const PIXEL_TO_CM = 0.0264;
let pointCounter = 0; // Counter for points
const messageDiv = document.getElementById("message");
// Function to draw a line segment
function drawSegment(start, end) {
ctx.beginPath();
ctx.moveTo(start.x, start.y);
ctx.lineTo(end.x, end.y);
ctx.stroke();
}
// Function to draw a point with alphabet label
function drawPointWithLabel(point, label) {
ctx.beginPath();
ctx.arc(point.x, point.y, 3, 0, 2 * Math.PI);
ctx.fill();
ctx.fillText(label, point.x + 5, point.y - 5);
}
// Function to draw reference grid lines and origin point
function drawReferenceGrid() {
ctx.strokeStyle = "#ddd";
ctx.lineWidth = 1;
// Draw vertical lines
for (let x = 10; x < canvas.width; x += 10) {
ctx.beginPath();
ctx.moveTo(x, 0);
ctx.lineTo(x, canvas.height);
ctx.stroke();
}
// Draw horizontal lines
for (let y = 10; y < canvas.height; y += 10) {
ctx.beginPath();
ctx.moveTo(0, y);
ctx.lineTo(canvas.width, y);
ctx.stroke();
}
// Draw origin point labeled 'O'
ctx.strokeStyle = "black";
ctx.lineWidth = 1;
}
// Function to redraw all points and segments
function redraw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawReferenceGrid();
for (const segment of segments) {
drawSegment(segment.start, segment.end);
}
for (let i = 0; i < points.length; i++) {
drawPointWithLabel(points[i], String.fromCharCode(65 + i));
}
updateDistanceLabels(); // Ensure distance labels are updated
updateAngleLabels(); // Ensure angle labels are updated
updateMessage(); // all messages are updated as per user action
}
// Function to find the nearest point within a certain distance
function findNearestPoint(x, y) {
let nearestPoint = null;
let minDistance = SNAP_DISTANCE;
for (const point of points) {
const distance = Math.sqrt(
Math.pow(point.x - x, 2) + Math.pow(point.y - y, 2)
);
if (distance < minDistance) {
minDistance = distance;
nearestPoint = point;
}
}
return nearestPoint;
}
// Function to check if a shape is closed
function isShapeClosed() {
if (segments.length < 3) return false;
const firstPoint = segments[0].start;
const lastPoint = segments[segments.length - 1].end;
const distance = Math.sqrt(
Math.pow(firstPoint.x - lastPoint.x, 2) +
Math.pow(firstPoint.y - lastPoint.y, 2)
);
return distance < SNAP_DISTANCE;
}
// Function to create a distance label
function createDistanceLabel(distance, x, y) {
const distanceLabel = document.createElement("div");
distanceLabel.className = "distanceLabel";
distanceLabel.style.left = `${x}px`;
distanceLabel.style.top = `${y}px`;
distanceLabel.textContent = `${distance.toFixed(2)} cm`;
document.body.appendChild(distanceLabel);
return distanceLabel;
}
// Function to update all distance labels
function updateDistanceLabels() {
const offset = 15; // Offset distance for the labels
for (let i = 0; i < distanceLabels.length; i++) {
const segment = segments[i];
const label = distanceLabels[i];
let midX =
(segment.start.x + segment.end.x) / 2 + canvas.offsetLeft;
let midY = (segment.start.y + segment.end.y) / 2 + canvas.offsetTop;
const distance =
Math.sqrt(
Math.pow(segment.end.x - segment.start.x, 2) +
Math.pow(segment.end.y - segment.start.y, 2)
) * PIXEL_TO_CM;
// Apply offset to the label position
const angle = Math.atan2(
segment.end.y - segment.start.y,
segment.end.x - segment.start.x
);
midX += offset * Math.cos(angle + Math.PI / 2);
midY += offset * Math.sin(angle + Math.PI / 2);
// Adjust position if label overlaps with the shape or other labels
let collision = true;
while (collision) {
collision = false;
for (let j = 0; j < distanceLabels.length; j++) {
if (j !== i) {
const otherLabel = distanceLabels[j];
const otherRect = otherLabel.getBoundingClientRect();
const labelRect = {
left: midX,
top: midY,
right: midX + otherRect.width,
bottom: midY + otherRect.height,
};
if (
labelRect.right > otherRect.left &&
labelRect.left < otherRect.right &&
labelRect.bottom > otherRect.top &&
labelRect.top < otherRect.bottom
) {
// Collision detected, move the label further
midX += offset * Math.cos(angle + Math.PI / 2);
midY += offset * Math.sin(angle + Math.PI / 2);
collision = true;
break;
}
}
}
}
label.style.left = `${midX}px`;
label.style.top = `${midY}px`;
label.textContent = `${distance.toFixed(2)} cm`;
}
}
// Function to calculate the angle between two vectors
function calculateAngle(p1, p2, p3) {
const v1 = { x: p1.x - p2.x, y: p1.y - p2.y };
const v2 = { x: p3.x - p2.x, y: p3.y - p2.y };
const dotProduct = v1.x * v2.x + v1.y * v2.y;
const magnitude1 = Math.sqrt(v1.x * v1.x + v1.y * v1.y);
const magnitude2 = Math.sqrt(v2.x * v2.x + v2.y * v2.y);
const angle = Math.acos(dotProduct / (magnitude1 * magnitude2));
return (angle * 180) / Math.PI;
}
// Function to determine if the angle is counterclockwise
function isCounterClockwise(p1, p2, p3) {
return (
(p3.x - p2.x) * (p1.y - p2.y) - (p3.y - p2.y) * (p1.x - p2.x) > 0
);
}
// Function to draw an arc for an angle
function drawAngleArc(p1, p2, p3, radius = 20) {
const angle1 = Math.atan2(p1.y - p2.y, p1.x - p2.x);
const angle2 = Math.atan2(p3.y - p2.y, p3.x - p2.x);
// Normalize angles to be within the range [0, 2*PI]
let startAngle = angle1 >= 0 ? angle1 : 2 * Math.PI + angle1;
let endAngle = angle2 >= 0 ? angle2 : 2 * Math.PI + angle2;
// Ensure the arc is always drawn in the smallest angle
if (endAngle < startAngle) {
endAngle += 2 * Math.PI;
}
if (endAngle - startAngle > Math.PI) {
[startAngle, endAngle] = [endAngle, startAngle];
endAngle += 2 * Math.PI;
}
ctx.beginPath();
ctx.arc(p2.x, p2.y, radius, startAngle, endAngle, false);
ctx.stroke();
return {
x: p2.x + radius * Math.cos((startAngle + endAngle) / 2),
y: p2.y + radius * Math.sin((startAngle + endAngle) / 2),
};
}
// Function to create an angle label
function createAngleLabel(angle, x, y) {
const angleLabel = document.createElement("div");
angleLabel.className = "angleLabel";
angleLabel.style.left = `${x}px`;
angleLabel.style.top = `${y}px`;
angleLabel.textContent = `${angle.toFixed(2)}°`;
document.body.appendChild(angleLabel);
return angleLabel;
}
// Function to update all angle labels
function updateAngleLabels() {
// Clear existing angle labels
angleLabels.forEach((label) => document.body.removeChild(label));
angleLabels.length = 0;
for (let i = 0; i < points.length; i++) {
const point = points[i];
const connectedSegments = segments.filter(
(segment) => segment.start === point || segment.end === point
);
if (connectedSegments.length >= 2) {
for (let j = 0; j < connectedSegments.length - 1; j++) {
const p1 =
connectedSegments[j].start === point
? connectedSegments[j].end
: connectedSegments[j].start;
const p2 =
connectedSegments[j + 1].start === point
? connectedSegments[j + 1].end
: connectedSegments[j + 1].start;
const angle = calculateAngle(p1, point, p2);
const arcPosition = drawAngleArc(p1, point, p2); // Draw the angle arc and get its position
// Offset for the label position
const labelOffset = 25; // Significantly increased offset
const labelAngle = Math.atan2(
arcPosition.y - point.y,
arcPosition.x - point.x
);
// Calculate the initial label position
let labelX =
arcPosition.x +
labelOffset * Math.cos(labelAngle) +
canvas.offsetLeft;
let labelY =
arcPosition.y +
labelOffset * Math.sin(labelAngle) +
canvas.offsetTop;
// Check if the label is overlapping with any point and adjust if necessary
const checkOverlapAndAdjust = (x, y) => {
for (const pt of points) {
const distance = Math.sqrt(
Math.pow(pt.x + canvas.offsetLeft - x, 2) +
Math.pow(pt.y + canvas.offsetTop - y, 2)
);
if (distance < labelOffset) {
// Adjust position if overlapping
x += labelOffset * Math.cos(labelAngle);
y += labelOffset * Math.sin(labelAngle);
}
}
return { x, y };
};
// Adjust label position to avoid overlap with points
const adjustedPosition = checkOverlapAndAdjust(labelX, labelY);
labelX = adjustedPosition.x;
labelY = adjustedPosition.y;
// Create and position the angle label
angleLabels.push(createAngleLabel(angle, labelX, labelY));
angleLabels.push(createAngleLabel(angle, labelX, labelY));
}
}
}
}
function updateMessage() {
let message = "";
if (segments.length === 0) {
message =
'To draw a line segment, start dragging from one point to another to create a line segment <span class="highlight bold">AB</span>.';
} else if (isShapeClosed()) {
const shapeNames = {
3: "Triangle",
4: "Quadrilateral",
5: "Pentagon",
6: "Hexagon",
7: "Heptagon",
8: "Octagon",
9: "Nonagon",
10: "Decagon",
11: "Hendecagon",
12: "Dodecagon",
13: "Tridecagon",
14: "Tetradecagon",
15: "Pentadecagon",
};
const lastSegment = segments[segments.length - 1];
const startPointLabel = String.fromCharCode(
65 + points.indexOf(lastSegment.start)
);
const endPointLabel = String.fromCharCode(
65 + points.indexOf(lastSegment.end)
);
const shapeName =
shapeNames[segments.length] || `${segments.length}-gon`;
const { expression } = calculatePerimeter();
const { perimeter } = calculatePerimeter();
const { area } = calculateArea();
message = `Wow! you have drawn a <span class="bold highlight">${shapeName}</span>.\nThe perimeter of the ${shapeName} is <span class='highlight'>${expression} = ${perimeter.toFixed(
2
)} cm</span> and its area is <span class='highlight'>${area.toFixed(
2
)} cm<sup>2</sup></span>`;
} else {
const lastPointLabel = String.fromCharCode(65 + points.length - 1);
message = `Now drag from <span class="highlight bold">point ${lastPointLabel}</span> to create a new segment..`;
}
messageDiv.innerHTML = message;
}
// Function to calculate the perimeter
function calculatePerimeter() {
let perimeter = 0;
let expression = "";
for (let i = 0; i < segments.length; i++) {
const segment = segments[i];
const distance =
Math.sqrt(
Math.pow(segment.end.x - segment.start.x, 2) +
Math.pow(segment.end.y - segment.start.y, 2)
) * PIXEL_TO_CM;
perimeter += distance;
const pointA = String.fromCharCode(65 + i);
const pointB = String.fromCharCode(65 + ((i + 1) % points.length));
expression += `${pointA}${pointB}(${distance.toFixed(2)} cm)`;
if (i < segments.length - 1) {
expression += " + ";
}
}
return { perimeter, expression };
}
// Function to calculate the area using the Shoelace formula
function calculateArea() {
let area = 0;
let expression = "";
for (let i = 0; i < points.length; i++) {
const currentPoint = points[i];
const nextPoint = points[(i + 1) % points.length];
const term1 = currentPoint.x * nextPoint.y;
const term2 = currentPoint.y * nextPoint.x;
area += term1 - term2;
const pointA = String.fromCharCode(65 + i);
const pointB = String.fromCharCode(65 + ((i + 1) % points.length));
expression += `(${pointA}.x * ${pointB}.y - ${pointA}.y * ${pointB}.x)`;
if (i < points.length - 1) {
expression += " + ";
}
}
area = (Math.abs(area) / 2) * PIXEL_TO_CM * PIXEL_TO_CM;
return { area, expression };
}
// Event listener for mouse down
canvas.addEventListener("mousedown", function (event) {
const mouseX = event.pageX - canvas.offsetLeft;
const mouseY = event.pageY - canvas.offsetTop;
const nearestPoint = findNearestPoint(mouseX, mouseY);
if (nearestPoint && isShapeClosed()) {
// Start dragging an existing point if the shape is closed
isPointDragging = true;
draggedPoint = nearestPoint;
} else if (!isShapeClosed()) {
if (nearestPoint) {
startPoint = nearestPoint;
} else {
startPoint = { x: mouseX, y: mouseY };
points.push(startPoint);
drawPointWithLabel(
startPoint,
String.fromCharCode(65 + pointCounter)
);
pointCounter++;
}
isDragging = true;
}
});
let tempAngleLabel = null;
let tempDistanceLabel = null;
// Event listener for mouse move
canvas.addEventListener("mousemove", function (event) {
if (isDragging && startPoint) {
const mouseX = event.pageX - canvas.offsetLeft;
const mouseY = event.pageY - canvas.offsetTop;
redraw();
drawSegment(startPoint, { x: mouseX, y: mouseY });
// Calculate and display distance
const tempEndPoint = { x: mouseX, y: mouseY };
const midX =
(startPoint.x + tempEndPoint.x) / 2 + canvas.offsetLeft;
const midY = (startPoint.y + tempEndPoint.y) / 2 + canvas.offsetTop;
const distance =
Math.sqrt(
Math.pow(tempEndPoint.x - startPoint.x, 2) +
Math.pow(tempEndPoint.y - startPoint.y, 2)
) * PIXEL_TO_CM;
// Remove previous temporary distance label
if (tempDistanceLabel) {
document.body.removeChild(tempDistanceLabel);
}
// Create and display new temporary distance label
tempDistanceLabel = createDistanceLabel(distance, midX, midY);
document.body.appendChild(tempDistanceLabel);
// Calculate and display angle if intersecting segments are found
if (segments.length > 0) {
const lastSegment = segments[segments.length - 1];
const angle = calculateAngle(
lastSegment.start,
lastSegment.end,
tempEndPoint
);
const arcPosition = drawAngleArc(
lastSegment.start,
lastSegment.end,
tempEndPoint
); // Draw the angle arc and get its position
// Remove previous temporary angle label
if (tempAngleLabel) {
document.body.removeChild(tempAngleLabel);
}
// Create and display new temporary angle label
tempAngleLabel = createAngleLabel(
angle,
arcPosition.x + canvas.offsetLeft,
arcPosition.y + canvas.offsetTop
);
document.body.appendChild(tempAngleLabel);
}
} else if (isPointDragging && draggedPoint) {
const mouseX = event.pageX - canvas.offsetLeft;
const mouseY = event.pageY - canvas.offsetTop;
draggedPoint.x = mouseX;
draggedPoint.y = mouseY;
redraw();
}
});
// Event listener for mouse up
canvas.addEventListener("mouseup", function (event) {
if (isDragging && startPoint) {
const mouseX = event.pageX - canvas.offsetLeft;
const mouseY = event.pageY - canvas.offsetTop;
const nearestPoint = findNearestPoint(mouseX, mouseY);
let endPoint;
if (nearestPoint && nearestPoint !== startPoint) {
// Snap to nearest existing point
endPoint = nearestPoint;
} else {
// Create a new end point
endPoint = { x: mouseX, y: mouseY };
points.push(endPoint);
drawPointWithLabel(
endPoint,
String.fromCharCode(65 + pointCounter)
);
pointCounter++;
}
segments.push({ start: startPoint, end: endPoint });
drawSegment(startPoint, endPoint);
const midX = (startPoint.x + endPoint.x) / 2 + canvas.offsetLeft;
const midY = (startPoint.y + endPoint.y) / 2 + canvas.offsetTop;
const distance =
Math.sqrt(
Math.pow(endPoint.x - startPoint.x, 2) +
Math.pow(endPoint.y - startPoint.y, 2)
) * PIXEL_TO_CM;
distanceLabels.push(createDistanceLabel(distance, midX, midY));
// Update angle labels if segments intersect
if (segments.length > 1) {
updateAngleLabels();
}
startPoint = null;
isDragging = false;
} else if (isPointDragging && draggedPoint) {
isPointDragging = false;
draggedPoint = null;
}
// Remove temporary distance and angle labels
if (tempDistanceLabel) {
document.body.removeChild(tempDistanceLabel);
tempDistanceLabel = null;
}
if (tempAngleLabel) {
document.body.removeChild(tempAngleLabel);
tempAngleLabel = null;
}
redraw(); // Redraw all points and segments to maintain the visual state
});
// Ensure that text is properly aligned and clear
ctx.textBaseline = "top";
ctx.font = "12px Arial";
// Initial draw to set up the grid
redraw();
// Reset Canvas Button Functionality
document
.getElementById("resetCanvas")
.addEventListener("click", function () {
segments.length = 0;
points.length = 0;
distanceLabels.forEach((label) => document.body.removeChild(label));
angleLabels.forEach((label) => document.body.removeChild(label));
distanceLabels.length = 0;
angleLabels.length = 0;
pointCounter = 0;
startPoint = null;
isDragging = false;
isPointDragging = false;
draggedPoint = null;
redraw();
});
// Undo Button Functionality
document
.getElementById("undoAction")
.addEventListener("click", function () {
if (segments.length > 0) {
const lastSegment = segments.pop();
// Remove the last distance label
distanceLabels.pop().remove();
// Check if the last point is only used by the last segment
const endPoint = lastSegment.end;
const startPoint = lastSegment.start;
const isEndPointUsedElsewhere = segments.some(
(segment) =>
segment.start === endPoint || segment.end === endPoint
);
const isStartPointUsedElsewhere = segments.some(
(segment) =>
segment.start === startPoint || segment.end === startPoint
);
if (!isEndPointUsedElsewhere) {
// Remove the last point if it's not used in any other segment
points.splice(points.indexOf(endPoint), 1);
pointCounter--;
}
if (!isStartPointUsedElsewhere) {
// Remove the start point if it's not used in any other segment
points.splice(points.indexOf(startPoint), 1);
pointCounter--;
}
// Remove angle labels associated with the removed segment
updateAngleLabels();
// Redraw everything
redraw();
}
// If no segments and only one point remains, clear the last point and remove angle labels
if (segments.length === 0 && points.length === 1) {
points.pop();
pointCounter = 0;
// Clear any angle labels if present
angleLabels.forEach((label) => document.body.removeChild(label));
angleLabels.length = 0;
redraw();
}
// If no segments and no points remain, remove all angle labels
if (segments.length === 0 && points.length === 0) {
angleLabels.forEach((label) => document.body.removeChild(label));
angleLabels.length = 0;
redraw();
}
});
};
</script>
</body>
</html>