-
Notifications
You must be signed in to change notification settings - Fork 24
/
script.js
715 lines (600 loc) · 20.8 KB
/
script.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
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
var color_choices = [
"#FF00FF",
"#8622FF",
"#FE0056",
"#00FFCE",
"#FF8000",
"#00B7EB",
"#FFFF00",
"#0E7AFE",
"#FFABAB",
"#0000FF",
"#CCCCCC",
];
// if you want choices to be kind of random, shuffle the array once here
var radiansPer45Degrees = Math.PI / 4;
var imageContainer = document.querySelector('.image-container');
var canvas = document.getElementById('canvas');
var mainCtx = canvas.getContext('2d');
var offScreenCanvas = document.createElement('canvas');
var offScreenCtx = offScreenCanvas.getContext('2d');
offScreenCanvas.width = canvas.width;
offScreenCanvas.height = canvas.height;
var img = new Image();
var rgb_color = color_choices[0];
var fill_color = 'rgba(0,0,0,0.35)';
var scaleFactor = 1;
var scaleSpeed = 0.01;
var points = [];
var masterPoints = [];
var masterColors = [];
var drawMode;
setDrawMode('polygon');
var constrainAngles = false;
var showNormalized = false;
function resetState() {
points = [];
masterPoints = [];
masterColors = [];
rgb_color = color_choices[0];
document.querySelector('#json').innerHTML = '';
document.querySelector('#python').innerHTML = '';
}
var isFullscreen = false;
var taskbarAndCanvas = document.querySelector('.right');
var editMode = false;
var selectedPointIndex = -1;
var selectedPolygonIndex = -1;
function blitCachedCanvas() {
mainCtx.clearRect(0, 0, canvas.width, canvas.height);
mainCtx.drawImage(offScreenCanvas, 0, 0);
}
function clipboard(selector) {
var copyText = document.querySelector(selector).innerText;
// strip whitespace on left and right
copyText = copyText.replace(/^\s+|\s+$/g, '');
navigator.clipboard.writeText(copyText);
}
function clearDrawings() {
offScreenCtx.clearRect(0, 0, offScreenCanvas.width, offScreenCanvas.height);
blitCachedCanvas();
}
function isClockwise(vertices) {
let sum = 0;
for (let i = 0; i < vertices.length; i++) {
const [x1, y1] = vertices[i];
const [x2, y2] = vertices[(i + 1) % vertices.length];
sum += (x2 - x1) * (y2 + y1);
}
return sum > 0;
}
function zoom(clicks) {
var newScaleFactor = scaleFactor + clicks * scaleSpeed;
newScaleFactor = Math.max(0.1, Math.min(newScaleFactor, 1));
const maxWidth = imageContainer.offsetWidth * 0.95;
const maxHeight = imageContainer.offsetHeight * 0.95;
let newWidth = img.width * newScaleFactor;
let newHeight = img.height * newScaleFactor;
if (newWidth > maxWidth) {
newHeight = (maxWidth / newWidth) * newHeight;
newWidth = maxWidth;
newScaleFactor = newWidth / img.width;
}
if (newHeight > maxHeight) {
newWidth = (maxHeight / newHeight) * newWidth;
newHeight = maxHeight;
newScaleFactor = newHeight / img.height;
}
scaleFactor = newScaleFactor;
canvas.style.width = newWidth + 'px';
canvas.style.height = newHeight + 'px';
}
function onPathClose() {
canvas.style.cursor = 'default';
// we do this to avoid clearing overlapping polygons
if (isClockwise(points)) {
points = points.reverse();
}
masterPoints.push(points);
points = [];
masterColors.push(rgb_color);
drawAllPolygons(offScreenCtx);
blitCachedCanvas();
rgb_color = color_choices[(masterColors.length) % (color_choices.length)];
}
// placeholder image
img.src = 'https://assets.website-files.com/5f6bc60e665f54545a1e52a5/63d3f236a6f0dae14cdf0063_drag-image-here.png';
img.onload = function() {
scaleFactor = 0.69;
canvas.style.width = img.width * scaleFactor + 'px';
canvas.style.height = img.height * scaleFactor + 'px';
canvas.width = img.width;
canvas.height = img.height;
offScreenCanvas.width = img.width;
offScreenCanvas.height = img.height;
offScreenCtx.drawImage(img, 0, 0);
blitCachedCanvas();
};
function makeLine(ctx, x1, y1, x2, y2) {
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
}
function drawNode(ctx, x, y, stroke = null) {
if (stroke) {
ctx.strokeStyle = stroke;
}
ctx.beginPath();
ctx.arc(x, y, 5, 0, 2 * Math.PI);
ctx.closePath();
ctx.fillStyle = 'white';
ctx.fill();
ctx.stroke();
}
function getScaledCoords(e) {
var rect = canvas.getBoundingClientRect();
var x = e.clientX - rect.left;
var y = e.clientY - rect.top;
return [x / scaleFactor, y / scaleFactor];
}
function drawAllPolygons(ctx) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0);
// draw polygons as subpaths and fill all at once
// we do this to avoid overlapping polygons becoming opaque
ctx.beginPath();
ctx.fillStyle = fill_color;
for (var i = 0; i < masterPoints.length; i++) {
var newpoints = masterPoints[i];
for (var j = 1; j < newpoints.length; j++) {
makeLine(ctx, newpoints[j - 1][0], newpoints[j - 1][1], newpoints[j][0], newpoints[j][1]);
ctx.moveTo(newpoints[0][0], newpoints[0][1]);
for (var j = 1; j < newpoints.length; j++) {
ctx.lineTo(newpoints[j][0], newpoints[j][1]);
}
makeLine(ctx, newpoints[newpoints.length - 1][0], newpoints[newpoints.length - 1][1], newpoints[0][0], newpoints[0][1]);
}
}
ctx.fill();
ctx.lineWidth = 5;
ctx.lineJoin = 'bevel';
for (var i = 0; i < masterPoints.length; i++) {
var newpoints = masterPoints[i];
ctx.strokeStyle = masterColors[i];
ctx.beginPath();
for (var j = 1; j < newpoints.length; j++) {
makeLine(ctx, newpoints[j - 1][0], newpoints[j - 1][1], newpoints[j][0], newpoints[j][1]);
ctx.moveTo(newpoints[0][0], newpoints[0][1]);
for (var j = 1; j < newpoints.length; j++) {
ctx.lineTo(newpoints[j][0], newpoints[j][1]);
}
}
ctx.closePath();
ctx.stroke();
// draw arc around each point
for (var j = 0; j < newpoints.length; j++) {
drawNode(ctx, newpoints[j][0], newpoints[j][1]);
}
}
}
function getParentPoints() {
var parentPoints = [];
for (var i = 0; i < masterPoints.length; i++) {
parentPoints.push(masterPoints[i]);
}
parentPoints.push(points);
return parentPoints;
}
function findClosestPoint(x, y) {
let minDist = Infinity;
let closestPoint = null;
let polygonIndex = -1;
let pointIndex = -1;
for (let i = 0; i < masterPoints.length; i++) {
for (let j = 0; j < masterPoints[i].length; j++) {
const [px, py] = masterPoints[i][j];
const dist = Math.sqrt((x - px) ** 2 + (y - py) ** 2);
if (dist < minDist && dist < 10 / scaleFactor) { // grab radius
minDist = dist;
closestPoint = [px, py];
polygonIndex = i;
pointIndex = j;
}
}
}
return { point: closestPoint, polygonIndex, pointIndex };
}
window.addEventListener('keyup', function(e) {
if (e.key === 'Shift') {
constrainAngles = false;
}
});
document.querySelector('#copyPythonButton').addEventListener('click', function(e) {
e.preventDefault();
clipboard("#python");
});
document.querySelector('#copyJSONButton').addEventListener('click', function(e) {
e.preventDefault();
clipboard("#json");
});
canvas.addEventListener('dragover', function(e) {
e.preventDefault();
});
canvas.addEventListener('wheel', function(e) {
e.preventDefault()
var delta = Math.sign(e.deltaY);
zoom(delta);
});
canvas.addEventListener('mouseleave', function(e) {
var xcoord = document.querySelector('#x');
var ycoord = document.querySelector('#y');
xcoord.innerHTML = '';
ycoord.innerHTML = '';
});
canvas.addEventListener('mousemove', function(e) {
var [x, y] = getScaledCoords(e);
x = Math.round(x);
y = Math.round(y);
// update x y coords
var xcoord = document.querySelector('#x');
var ycoord = document.querySelector('#y');
if(constrainAngles && points.length > 0) {
var lastPoint = points[points.length - 1];
var dx = x - lastPoint[0];
var dy = y - lastPoint[1];
var angle = Math.atan2(dy, dx);
var length = Math.sqrt(dx * dx + dy * dy);
const snappedAngle = Math.round(angle / radiansPer45Degrees) * radiansPer45Degrees;
var new_x = lastPoint[0] + length * Math.cos(snappedAngle);
var new_y = lastPoint[1] + length * Math.sin(snappedAngle);
x = Math.round(new_x);
y = Math.round(new_y);
}
// sometimes, a mousemove event is leaving the canvas and has coordinates outside the canvas
// however, due to the cursors being used, we do not need to check if it is larger than canvas.width or canvas.height
if (x < 0 || y < 0 ){
xcoord.innerHTML = '';
ycoord.innerHTML = '';
return;
}
xcoord.innerHTML = x;
ycoord.innerHTML = y;
var ctx = mainCtx;
ctx.lineWidth = 5;
ctx.lineJoin = 'bevel';
ctx.fillStyle = 'white';
// if cursor is crosshair, draw line from last point to cursor
if (canvas.style.cursor == 'crosshair') {
blitCachedCanvas();
for (var i = 0; i < points.length - 1; i++) {
ctx.strokeStyle = rgb_color;
ctx.beginPath();
ctx.lineJoin = 'bevel';
makeLine(ctx, points[i][0], points[i][1], points[i + 1][0], points[i + 1][1]);
ctx.closePath();
ctx.stroke();
drawNode(ctx, points[i][0], points[i][1]);
}
if ((points.length > 0 && drawMode == "polygon") || (points.length > 0 && points.length < 2 && drawMode == "line")) {
ctx.beginPath();
ctx.lineJoin = 'bevel';
ctx.strokeStyle = rgb_color;
makeLine(ctx, points[points.length - 1][0], points[points.length - 1][1], x, y);
ctx.closePath();
ctx.stroke();
drawNode(ctx, points[i][0], points[i][1]);
}
}
if (editMode && selectedPointIndex !== -1) {
masterPoints[selectedPolygonIndex][selectedPointIndex] = [x, y];
drawAllPolygons(offScreenCtx);
blitCachedCanvas();
writePoints(getParentPoints());
}
});
canvas.addEventListener('drop', function(e) {
e.preventDefault();
var file = e.dataTransfer.files[0];
// only allow image files
var supportedImageTypes = ['image/png', 'image/jpeg', 'image/jpg', 'image/webp'];
if (!supportedImageTypes.includes(file.type)) {
alert('Only PNG, JPEG, JPG, and WebP files are allowed.');
return;
}
var reader = new FileReader();
reader.onload = function(event) {
img.src = event.target.result;
};
reader.readAsDataURL(file);
img.onload = function() {
// reset state to initial values
resetState();
// draw loaded image on canvas
scaleFactor = 0.25;
canvas.style.width = img.width * scaleFactor + 'px';
canvas.style.height = img.height * scaleFactor + 'px';
canvas.width = img.width;
canvas.height = img.height;
offScreenCanvas.width = img.width;
offScreenCanvas.height = img.height;
const maxWidth = imageContainer.offsetWidth * 0.95;
const maxHeight = imageContainer.offsetHeight * 0.95;
let newWidth = img.width;
let newHeight = img.height;
if (newWidth > maxWidth) {
newHeight = (maxWidth / newWidth) * newHeight;
newWidth = maxWidth;
}
if (newHeight > maxHeight) {
newWidth = (maxHeight / newHeight) * newWidth;
newHeight = maxHeight;
}
scaleFactor = newWidth / img.width;
canvas.style.width = newWidth + 'px';
canvas.style.height = newHeight + 'px';
canvas.style.borderRadius = '10px';
offScreenCtx.drawImage(img, 0, 0);
blitCachedCanvas();
};
});
function writePoints(parentPoints) {
var normalized = [];
// if normalized is true, normalize all points
var imgHeight = img.height;
var imgWidth = img.width;
if (showNormalized) {
for (var i = 0; i < parentPoints.length; i++) {
var normalizedPoints = [];
for (var j = 0; j < parentPoints[i].length; j++) {
normalizedPoints.push([
Math.round(parentPoints[i][j][0] / imgWidth * 100) / 100,
Math.round(parentPoints[i][j][1] / imgHeight * 100) / 100
]);
}
normalized.push(normalizedPoints);
}
parentPoints = normalized;
}
// clean empty points
parentPoints = parentPoints.filter(points => !!points.length);
if (!parentPoints.length) {
document.querySelector('#python').innerHTML = '';
document.querySelector('#json').innerHTML;
return;
}
// create np.array list
var code_template = `[\n${parentPoints.map(function(points) {
return ` np.array([${points.map(function(point) {
return `[${point[0]}, ${point[1]}]`;}).join(', ')}])`;
}).join(',\n')}\n]`;
document.querySelector('#python').innerHTML = code_template;
var json_template = `{\n${parentPoints.map(function(points) {
return ` [${points.map(function(point) {
return `{"x": ${point[0]}, "y": ${point[1]}}`;}).join(', ')}]`;
}).join(',\n')}\n}`;
document.querySelector('#json').innerHTML = json_template;
}
canvas.addEventListener('mousedown', function(e) {
var [x, y] = getScaledCoords(e);
x = Math.round(x);
y = Math.round(y);
if (editMode) {
const { point, polygonIndex, pointIndex } = findClosestPoint(x, y);
if (point) {
selectedPointIndex = pointIndex;
selectedPolygonIndex = polygonIndex;
canvas.style.cursor = 'grabbing';
}
} else {
// click handling for drawing mode
canvas.style.cursor = 'crosshair';
if(constrainAngles && points.length > 0) {
var lastPoint = points[points.length - 1];
var dx = x - lastPoint[0];
var dy = y - lastPoint[1];
var angle = Math.atan2(dy, dx);
var length = Math.sqrt(dx * dx + dy * dy);
const snappedAngle = Math.round(angle / radiansPer45Degrees) * radiansPer45Degrees;
var new_x = lastPoint[0] + length * Math.cos(snappedAngle);
var new_y = lastPoint[1] + length * Math.sin(snappedAngle);
x = Math.round(new_x);
y = Math.round(new_y);
}
if (points.length > 2 && drawMode == "polygon") {
distX = x - points[0][0];
distY = y - points[0][1];
// stroke is 3px and centered on the circle (i.e. 1/2 * 3px) and arc radius is
if(Math.sqrt(distX * distX + distY * distY) <= 6.5) {
onPathClose();
return;
}
}
points.push([x, y]);
drawNode(mainCtx, x, y, rgb_color);
if(drawMode == "line" && points.length == 2) {
onPathClose();
}
// concat all points into one array
var parentPoints = [];
for (var i = 0; i < masterPoints.length; i++) {
parentPoints.push(masterPoints[i]);
}
// add "points"
if(points.length > 0) {
parentPoints.push(points);
}
writePoints(parentPoints);
}
});
canvas.addEventListener('mouseup', function(e) {
if (editMode) {
selectedPointIndex = -1;
selectedPolygonIndex = -1;
canvas.style.cursor = 'move';
}
});
document.querySelector('#normalize-checkbox').addEventListener('change', function(e) {
showNormalized = e.target.checked;
var parentPoints = getParentPoints();
writePoints(parentPoints);
});
function setDrawMode(mode) {
drawMode = mode;
setEditMode(false);
canvas.style.cursor = 'crosshair';
document.querySelectorAll('.t-mode').forEach(el => el.classList.remove('active'));
document.querySelector(`#mode-${mode}`).classList.add('active');
}
function setEditMode(editEnabled) {
editMode = editEnabled;
canvas.style.cursor = editEnabled ? 'move' : 'crosshair';
document.querySelectorAll('.t-mode').forEach(el => el.classList.remove('active'));
document.querySelector(`#mode-${editEnabled ? 'edit' : drawMode}`).classList.add('active');
}
document.querySelector('#mode-polygon').addEventListener('click', function(e) {
setDrawMode('polygon');
})
document.querySelector('#mode-line').addEventListener('click', function(e) {
setDrawMode('line');
})
document.querySelector('#mode-edit').addEventListener('click', function(e) {
setEditMode(true);
});
document.addEventListener('keydown', function(e) {
if (e.key == 'l' || e.key == 'L') {
setDrawMode('line');
}
if (e.key == 'p' || e.key == 'P') {
setDrawMode('polygon');
}
if (e.key == 'e' || e.key == 'E') {
setEditMode(true);
}
});
function rewritePoints() {
var parentPoints = getParentPoints();
writePoints(parentPoints);
}
function highlightButtonInteraction (buttonId) {
document.querySelector(buttonId).classList.add('active');
setTimeout(() => document.querySelector(buttonId).classList.remove('active'), 100);
}
function undo() {
highlightButtonInteraction('#undo');
if (points.length > 0) {
points.pop();
blitCachedCanvas();
rewritePoints();
if(points.length === 0){
return;
}
var ctx = mainCtx;
ctx.strokeStyle = rgb_color;
ctx.fillStyle = 'white';
if (points.length === 1) {
drawNode(ctx, points[0][0], points[0][1]);
}
else {
drawNode(ctx, points[0][0], points[0][1]);
for (var i = 0; i < points.length - 1; i++) {
makeLine(ctx, points[i][0], points[i][1], points[i + 1][0], points[i + 1][1]);
ctx.stroke();
drawNode(ctx, points[i + 1][0], points[i + 1][1]);
}
}
}
}
document.querySelector('#undo').addEventListener('click', function(e) {
undo();
})
function discardCurrentPolygon () {
highlightButtonInteraction('#discard-current');
points = [];
blitCachedCanvas();
rewritePoints();
}
document.querySelector('#discard-current').addEventListener('click', function(e) {
discardCurrentPolygon();
})
function clearAll() {
highlightButtonInteraction('#clear')
resetState();
// reset main and offscreen canvases
mainCtx.clearRect(0, 0, canvas.width, canvas.height);
offScreenCtx.clearRect(0, 0, offScreenCanvas.width, offScreenCanvas.height);
mainCtx.drawImage(img, 0, 0);
offScreenCtx.drawImage(img, 0, 0);
points = [];
masterPoints = [];
masterColors = [];
rgb_color = color_choices[0];
document.querySelector('#jsonCode').innerHTML = '';
document.querySelector('#pythonCode').innerHTML = '';
}
document.querySelector('#clear').addEventListener('click', function(e) {
clearAll();
})
function saveImage () {
highlightButtonInteraction('#save-image');
var link = document.createElement('a');
link.download = 'image.png';
link.href = canvas.toDataURL();
link.click();
}
document.querySelector('#save-image').addEventListener('click', function(e) {
saveImage();
})
function toggleFullscreen() {
highlightButtonInteraction('#fullscreen');
if (!isFullscreen) {
if (taskbarAndCanvas.requestFullscreen) {
taskbarAndCanvas.requestFullscreen();
} else if (taskbarAndCanvas.webkitRequestFullscreen) { // Safari
taskbarAndCanvas.webkitRequestFullscreen();
} else if (taskbarAndCanvas.msRequestFullscreen) { // IE/Edge
taskbarAndCanvas.msRequestFullscreen();
}
} else {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.webkitExitFullscreen) { // Safari
document.webkitExitFullscreen();
} else if (document.msExitFullscreen) { // IE/Edge
document.msExitFullscreen();
}
}
}
document.addEventListener('fullscreenchange', function() {
isFullscreen = document.fullscreenElement !== null;
});
document.querySelector('#fullscreen').addEventListener('click', function(e) {
toggleFullscreen();
});
window.addEventListener('keydown', function(e) {
if (e.key === 'z' && (e.ctrlKey || e.metaKey)) {
e.preventDefault();
e.stopImmediatePropagation();
undo();
}
if (e.key === 'Shift') {
constrainAngles = true;
}
if (e.key === 'Escape') {
discardCurrentPolygon();
}
if (e.key === 'e' && (e.ctrlKey || e.metaKey)) {
clearAll();
}
if (e.key === 's' && (e.ctrlKey || e.metaKey)) {
e.preventDefault();
e.stopImmediatePropagation();
saveImage();
}
if (e.key === 'Enter') {
if(points.length > 2) {
onPathClose();
}
}
if (e.key === 'f' || e.key === 'F') {
toggleFullscreen();
}
})