forked from pfirpfel/image-viewer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathviewer.js
1279 lines (1097 loc) · 40.7 KB
/
viewer.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
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function (window) {
"use strict";
function ImageViewer(canvasId, imageUrl, options){
var self = this;
// options-object
// possible start options:
// * mode: string (other than default viewer-only mode)
// - 'editAnswer' : displays answer and answer related buttons
// - 'editSolution' : displays solution and solution related buttons
// - 'showSolution' : displays answer and solution
// - 'editAnnotations' : displays annotations and related edit-buttons
// - 'showAnnotations' : displays annotations
//
// * answer: position-object, like { x: 0; y: 0; }
// position of answer inside the image
//
// * solution: array of positions, like [{ x: 0; y: 0; }, { x: 1; y: 1; }]
// the positions represent vertices which make up the solution
// polygon
//
// * annotations: array of annotation-objects, example:
// [
// {
// polygon: [{ x: 0; y: 0; }, { x: 1; y: 1; }, { x: 2; y: 2; }, { x: 0; y: 0; }],
// color: '#00FF00'
// }
// ]
//
// * annotationColors: array of CSS color values, defines the predefined set of colors
// used for annotations.
//
options = (typeof options === 'object') ? options : {};
// sanitize options.mode once
options.mode = (typeof options.mode === 'string') ? options.mode : "";
// canvas
var canvas = document.getElementById(canvasId)
, context = canvas.getContext("2d")
// dirty state
, dirty = true
// flag to stop render loop
, stopRendering = false
// image scale
, scale = 1
, scaleStep = 0.1
// image centre (scroll offset)
, centre = { x: 0, y: 0 }
// drawing settings
, defaultLineWidth = 3
// viewer states
, states = {
DEFAULT: 0,
ANSWER_DRAW: 1,
POLYGON_DRAW: 2,
POLYGON_MOVE: 3,
POLYGON_POINT_DELETE: 4,
ANNOTATION_DISPLAY: 5
}
, state = states.ANSWER_DRAW
// keeping track of event handling
, events = []
//// buttons
// default buttons that are always visible
, zoomOutButton = new Button('\uf010', 'Zoom out')
, zoomInButton = new Button('\uf00e', 'Zoom in')
, defaultButtons = [zoomOutButton, zoomInButton]
// buttons for answer feature
, deleteAnswerButton = new Button('\uf1f8', 'Delete answer')
, addAnswerButton = new Button('\uf024', 'Set answer')
, answerButtons = [deleteAnswerButton, addAnswerButton]
// buttons for the solution feature
, drawSolutionPointButton = new Button('\uf040', 'Draw new solution point (close with shift-click)')
, moveSolutionButton = new Button('\uf047', 'Move solution point')
, deleteSolutionPointButton = new Button('\uf00d', 'Delete solution point')
, deleteSolutionButton = new Button('\uf1f8', 'Delete solution')
, solutionButtons = [deleteSolutionButton,
deleteSolutionPointButton,
moveSolutionButton,
drawSolutionPointButton]
// buttons for the annotations feature
, addNewAnnotationButton = new Button('\uf067', 'Start drawing a new annotation')
, drawAnnotationPointButton = new Button('\uf040', 'Draw new annotation point (close with shift-click)')
, moveAnnotationButton = new Button('\uf047', 'Move annotation point')
, deleteAnnotationPointButton = new Button('\uf00d', 'Delete annotation point')
, deleteAnnotationButton = new Button('\uf1f8', 'Delete active annotation')
, annotationButtons = [ deleteAnnotationButton,
deleteAnnotationPointButton,
moveAnnotationButton,
drawAnnotationPointButton,
addNewAnnotationButton]
// contains all active buttons
, buttons = defaultButtons.slice()
// contains all active color buttons (for coloring annotations)
, colorButtons = []
// current tool tip (used to track change of tool tip)
, currentTooltip = null
// Input handling
// active element (mainly) used for dragging
, activeMoveElement = centre
// track state of left mouse button (even outside the canvas)
, leftMouseButtonDown = false
// keep last mouse position to calculate drag distance
, mouseLastPos = null
// UI element which is currently in focus, i.e. the mouse is hovering over it
, focusUIElement = null
// active polygon in edit mode
, activePolygon = null
// answer feature
, answerEditable = options.mode === 'editAnswer'
, answerVisible = answerEditable || options.mode === 'showSolution'
// solution feature
, solutionEditable = options.mode === 'editSolution'
, solutionVisible = solutionEditable || options.mode === 'showSolution'
// annotation feature
, annotationsEditable = options.mode === 'editAnnotations'
, annotationsVisible = annotationsEditable || options.mode === 'showAnnotations'
, annotationColors = options.annotationColors || [
'#8dd3c7',
'#ffffb3',
'#bebada',
'#fb8072',
'#80b1d3',
'#fdb462'
];
// image
this.image = new Image();
// answer
this.answer = (typeof options.answer === 'object' && options.answer !== null) ? options.answer : null;
// solution
this.solution = null;
// annotations
// format: { polygon: Polygon-object, color: color-string }
this.annotations = [];
function isState(checkState){
return state === states[checkState];
}
function importPolygon(vertexArray){
if(vertexArray.length < 1){
return new Polygon();
}
var initialVertex = createVertex(vertexArray[0].x, vertexArray[0].y)
, current = initialVertex
, next = null;
for(var i = 1; i < vertexArray.length; i++){
next = createVertex(vertexArray[i].x, vertexArray[i].y);
if(next.equals(initialVertex)){
current.next = initialVertex;
break;
}
current.next = next;
current = next;
}
return new Polygon(initialVertex);
}
function exportPolygon(polygon){
// return empty array if polygon is empty
if(typeof polygon === 'undefined' || polygon === null) return [];
var exportedPolygon = [];
var vertices = polygon.getVertices();
//if closed path, add start point at the end again
if(vertices[vertices.length - 1].next === vertices[0]) vertices.push(vertices[0]);
for(var i = 0; i < vertices.length; i++){
exportedPolygon.push({
x: vertices[i].position.x,
y: vertices[i].position.y
});
}
return exportedPolygon;
}
this.exportSolution = function(){
return exportPolygon(this.solution);
};
this.importSolution = function(importedSolution){
this.solution = activePolygon = (importedSolution.length >= 1) ? importPolygon(importedSolution) : null;
dirty = true;
};
this.exportAnnotations = function(){
return this.annotations.map(function(annotation){
return {
color: annotation.color,
polygon: exportPolygon(annotation.polygon)
};
});
};
this.importAnnotations = function(importedAnnotations){
importedAnnotations.forEach(function(importAnnotation){
addNewAnnotation(importPolygon(importAnnotation.polygon), importAnnotation.color);
});
};
// gets called if the solution changes
this.onSolutionChange = function(solution){};
// gets called if one or more of the annotations change
this.onAnnotationChange = function(annotations){};
function onImageLoad(){
// set scale to use as much space inside the canvas as possible
if(((canvas.height / self.image.height) * self.image.width) <= canvas.width){
scale = canvas.height / self.image.height;
} else {
scale = canvas.width / self.image.width;
}
// centre at image centre
centre.x = self.image.width / 2;
centre.y = self.image.height / 2;
// image changed
dirty = true;
// start new render loop
render();
}
this.zoomIn = function(){
scale = scale * (1 + scaleStep);
dirty = true;
};
this.zoomOut = function(){
scale = scale * (1 - scaleStep);
dirty = true;
};
function render(){
// only re-render if dirty
if(dirty){
dirty = false;
var ctx = context;
// clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// draw image (transformed and scaled)
ctx.save();
var translateX = canvas.width / 2 - centre.x * scale
, translateY = canvas.height / 2 - centre.y * scale;
ctx.translate(translateX, translateY);
ctx.scale(scale, scale);
ctx.drawImage(self.image, 0,0);
ctx.restore();
// draw solution
if(solutionVisible && self.solution !== null){
drawPolygon(ctx, self.solution);
}
// draw annotations
if(annotationsVisible){
self.annotations.forEach(function(annotation){
drawPolygon(ctx, annotation.polygon, annotation.color);
});
}
// draw line to mouse cursor
if((solutionEditable || annotationsEditable)
&& activePolygon !== null
&& activePolygon.getLength() > 0
&& !activePolygon.isClosed()){
var lastVertexPosition = activePolygon.getLastVertex().position
, mousePosition = convertToImagePosition(mouseLastPos);
drawLine(ctx, lastVertexPosition, mousePosition, '#FF3300', defaultLineWidth);
}
// draw answer
if(answerVisible && self.answer !== null){
drawAnswer(ctx);
}
// draw buttons
drawButtons(ctx);
}
if(!stopRendering) window.requestAnimationFrame(render);
}
function drawLine(ctx, from, to, lineColor, lineWidth){
/**
* ctx: canvas context
* from: start-vertex, in image coordinates
* to: end-vertex, in image coordinates
* lineColor: color string
* lineWidth: number, width in pixel
*/
ctx.save();
// style
ctx.strokeStyle = lineColor;
ctx.lineWidth = lineWidth;
// draw the line
var translation = convertToCanvasTranslation(from)
, relativeToPosition = {
x: to.x - from.x,
y: to.y - from.y
}
, drawPos = { x: 0, y: 0};
ctx.translate(translation.x, translation.y);
ctx.scale(scale, scale);
ctx.beginPath();
ctx.moveTo(drawPos.x, drawPos.y);
ctx.lineTo(relativeToPosition.x, relativeToPosition.y);
ctx.stroke();
ctx.restore();
}
function drawButtons(ctx){
var padding = 10
, radius = 20
, gap = 2 * radius + padding
, x = canvas.width - radius - padding
, y = canvas.height - radius - padding
, i;
// draw buttons
for(i = 0; i < buttons.length; i++){
buttons[i].draw(ctx, x, y - gap * i, radius);
}
// draw color buttons
// ---
// set starting coordinates in lower left corner
x = radius + padding;
y = canvas.height - radius - padding;
for(i = 0; i < colorButtons.length; i++){
colorButtons[i].draw(ctx, x, y - gap * i, radius);
}
// draw tooltip
if(currentTooltip !== null){
ctx.save();
ctx.globalAlpha = 0.5;
var fontSize = radius;
ctx.font = fontSize + "px sans-serif";
// calculate position
var textSize = ctx.measureText(currentTooltip).width
, rectWidth = textSize + padding
, rectHeight = fontSize * 0.70 + padding
, rectX = canvas.width
- (2 * radius + 2 * padding) // buttons
- rectWidth
, rectY = canvas.height - rectHeight - padding
, textX = rectX + 0.5 * padding
, textY = canvas.height - 1.5 * padding;
ctx.fillStyle = '#000000';
drawRoundRectangle(ctx, rectX, rectY, rectWidth, rectHeight, 8, true, false);
ctx.fillStyle = '#ffffff';
ctx.fillText(currentTooltip, textX, textY);
ctx.restore();
}
}
function drawRoundRectangle(ctx, x, y, width, height, radius, fill, stroke){
radius = (typeof radius === 'number') ? radius : 5;
fill = (typeof fill === 'boolean') ? fill : true; // fill = default
stroke = (typeof stroke === 'boolean') ? stroke : false;
// draw round rectangle
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + width - radius, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
ctx.lineTo(x + width, y + height - radius);
ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
ctx.lineTo(x + radius, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
ctx.lineTo(x, y + radius);
ctx.quadraticCurveTo(x, y, x + radius, y);
ctx.closePath();
if(fill) ctx.fill();
if(stroke) ctx.stroke();
}
function convertToImagePosition(canvasPosition){
var visiblePart = {
x: centre.x >= (canvas.width / scale / 2) ? centre.x - canvas.width / scale / 2 : 0,
y: centre.y >= (canvas.height / scale / 2) ? centre.y - canvas.height / scale / 2 : 0
}
, canvasImage = {
x: (centre.x >= (canvas.width / scale / 2)) ? 0 : canvas.width / 2 - centre.x * scale,
y: (centre.y >= (canvas.height / scale / 2)) ? 0 : canvas.height / 2 - centre.y * scale
}
, imagePosition = {};
imagePosition.x =
visiblePart.x // image offset
+ canvasPosition.x / scale // de-scaled canvas position
- canvasImage.x / scale; // de-scaled canvas offset
imagePosition.y =
visiblePart.y // image offset
+ canvasPosition.y / scale // de-scaled canvas position
- canvasImage.y / scale; // de-scaled canvas offset
return imagePosition;
}
function convertToCanvasTranslation(imagePosition){
return {
x: (
imagePosition.x // x-position on picture
+ canvas.width / scale / 2 // offset of scaled canvas
- centre.x // scroll offset of image
) * scale, // scale the transformation
y: (
imagePosition.y // y-position on picture
+ canvas.height / scale / 2 // offset of scaled canvas
- centre.y // scroll offset of image
) * scale // scale the transformation
};
}
function createVertex(x, y, polygon){
var newVertex = new Vertex(x, y, polygon);
newVertex.onClick = function(evt){
if(isState('POLYGON_POINT_DELETE')){
if(newVertex.polygon !== null){
newVertex.polygon.deleteVertex(newVertex);
if(newVertex.polygon === self.solution){
self.onSolutionChange(self.exportSolution());
} else {
cleanupAnnotations();
self.onAnnotationChange(self.exportAnnotations());
}
// FIXME: if this reduced the polygon to two or less vertices, delete the polygon
dirty = true;
}
return false;
}
if(isState('POLYGON_DRAW')){
var isInitialVertex = newVertex.polygon !== null
&& newVertex.equals(newVertex.polygon.initialVertex);
if(isInitialVertex && newVertex.polygon.getLength() > 2){
newVertex.polygon.close();
state = states.DEFAULT;
if(newVertex.polygon === self.solution){
self.onSolutionChange(self.exportSolution());
} else {
cleanupAnnotations();
self.onAnnotationChange(self.exportAnnotations());
}
return false;
}
}
return true;
};
newVertex.onMouseDown = function(){
if(isState('POLYGON_MOVE')){
activeMoveElement = newVertex.position;
leftMouseButtonDown = true;
return true;
}
return false;
};
return newVertex;
}
function Vertex(x, y, polygon) {
var vertexInstance = this;
this.position = {
x: x,
y: y
};
this.polygon = polygon || null;
this.next = null;
this.handleWidth = 12; // also used as bounding box
this.onClick = function(evt){ return true; }; // just bubble on default
this.onMouseDown = function(){};
}
Vertex.prototype.equals = function(other){
return this.position.x === other.position.x
&& this.position.y === other.position.y;
};
Vertex.prototype.isWithinBounds = function(x, y){
var canvasPosition = convertToCanvasTranslation(this.position);
return x >= canvasPosition.x - this.handleWidth / 2 && x <= canvasPosition.x + this.handleWidth / 2
&& y >= canvasPosition.y - this.handleWidth / 2 && y <= canvasPosition.y + this.handleWidth / 2;
};
function drawVertexHandle(ctx, vertex){
// preserve context
ctx.save();
var translation = convertToCanvasTranslation(vertex.position);
ctx.translate(translation.x, translation.y);
ctx.fillStyle = (vertex === focusUIElement
&& vertex === activePolygon.initialVertex
&& isState('POLYGON_DRAW'))
? '#FF6600' // if mouse is hovering over this and a click would close the polygon
: '#FFFFFF'; // default
ctx.strokeStyle = '#000000';
ctx.beginPath();
ctx.rect(-vertex.handleWidth/2, // x
-vertex.handleWidth/2, // y
vertex.handleWidth, // width
vertex.handleWidth); // height
ctx.stroke();
ctx.fill();
// restore context
ctx.restore();
}
function Polygon(initialVertex){
var polygonInstance = this;
this.initialVertex = initialVertex || null;
this.onMouseDown = function(evt){
return false;
};
this.onClick = function(evt){
if(solutionEditable || annotationsEditable){
activePolygon = polygonInstance;
dirty = true;
return false; // don't bubble
} else {
return true; // bubble
}
};
}
Polygon.prototype.addVertex = function(vertex){
if(this.initialVertex !== null){
var last = this.initialVertex;
while(last.next !== null && last.next !== this.initialVertex){
last = last.next;
}
last.next = vertex;
} else {
this.initialVertex = vertex;
}
vertex.polygon = this;
dirty = true;
};
Polygon.prototype.deleteVertex = function(vertex){
if(this.initialVertex !== null && this.initialVertex.equals(vertex)){
this.initialVertex = this.initialVertex.next;
} else {
var deleted = false
, current = this.initialVertex
, next = current.next;
while(!deleted && next !== null && next !== this.initialVertex){
if(next.equals(vertex)){
current.next = next.next;
deleted = true;
} else {
current = next;
next = current.next;
}
}
}
};
Polygon.prototype.getVertices = function(){
var vertices = [], currentVertex = this.initialVertex;
while(currentVertex !== null){
if(vertices.indexOf(currentVertex) === -1){
vertices.push(currentVertex);
}
currentVertex = (currentVertex.next !== this.initialVertex) ? currentVertex.next : null;
}
return vertices;
};
function drawPolygon(ctx, polygon, fillColor, strokeColor){
// only draw lines or polygon if there is more than one vertex
if(polygon.initialVertex !== null && polygon.initialVertex.next !== null){
var drawPos = { x: 0, y: 0}
, current = polygon.initialVertex
, next
, translation = convertToCanvasTranslation(polygon.initialVertex.position)
;
ctx.save();
ctx.globalAlpha = 0.7;
ctx.translate(translation.x, translation.y);
ctx.scale(scale, scale);
ctx.beginPath();
ctx.moveTo(drawPos.x, drawPos.y);
do {
next = current.next;
drawPos = {
x: drawPos.x + (next.position.x - current.position.x),
y: drawPos.y + (next.position.y - current.position.y)
};
ctx.lineTo(drawPos.x, drawPos.y);
current = next;
} while(current.next !== null && current !== polygon.initialVertex);
ctx.fillStyle = fillColor || '#0000FF';
ctx.strokeStyle = strokeColor || '#66FF33';
if(current === polygon.initialVertex){
ctx.strokeStyle = strokeColor || '#000000';
ctx.closePath();
ctx.fill();
}
ctx.lineWidth = defaultLineWidth;
ctx.stroke();
ctx.restore();
}
// draw handles
if((polygon === activePolygon && (solutionEditable || annotationsEditable))){
polygon.getVertices().forEach(function(handle){
drawVertexHandle(ctx, handle);
});
}
}
Polygon.prototype.isClosed = function(){
var current = this.initialVertex;
if(current === null) return false;
var count = 0;
while(current.next !== null && current.next !== this.initialVertex){
current = current.next;
count++;
}
return current.next === this.initialVertex // last vertex has to be same as the first
&& count > 1; // at least to other vertices have to be traversed before returning,
// otherwise it would only be a line
};
Polygon.prototype.getLastVertex = function(){
var current = this.initialVertex;
if(current === null) return null;
while(current.next !== null && current.next !== this.initialVertex) current = current.next;
return current;
};
Polygon.prototype.getLength = function(){
if(this.initialVertex === null) return 0;
var length = 1;
var current = this.initialVertex;
while(current.next !== null && current.next !== this.initialVertex){
current = current.next;
length++;
}
return length;
};
function isLeft(p0, p1, p2){
// p0, p1, p2: point objects, like { x: 0, y: 0 }
// returns:
// >0 : for p2 left of the line through p0 and p1
// =0 : for p2 on the line
// <0 : for p2 right of the line
// see: http://geomalgorithms.com/a01-_area.html
return ( (p1.x - p0.x) * (p2.y - p0.y) - (p2.x - p0.x) * (p1.y - p0.y));
}
Polygon.prototype.isWithinBounds = function(x, y){
// get all vertices
var vertices = this.getVertices()
// winding number
, wn = 0
// point to check
, p = convertToImagePosition({ x: x, y: y });
// if polygon is not closed, the coordinates can't be within bounds
if(vertices.length < 3 || vertices[vertices.length - 1].next !== vertices[0]) return false;
// adding start point again (too include last, closing edge)
vertices.push(vertices[0]);
// algorithm see: http://geomalgorithms.com/a03-_inclusion.html
for(var i = 0; i + 1 < vertices.length; i++){ // edge from vertices[i] to vertices[i+1]
if(vertices[i].position.y <= p.y){ // start y <= p.y
if(vertices[i + 1].position.y > p.y){ // an upward crossing
if(isLeft(vertices[i].position, vertices[i + 1].position, p) > 0){ // P left of edge
wn++; // have a valid up intersect
}
}
} else { // start y > p.y
if(vertices[i + 1].position.y <= p.y){ // a downward crossing
if(isLeft(vertices[i].position, vertices[i + 1].position, p) < 0){ // P right of edge
wn--; // have a valid down intersect
}
}
}
}
// wn == 0 only when p is outside
return wn !== 0;
};
Polygon.prototype.close = function(){
if(this.getVertices().length > 2){
this.addVertex(this.initialVertex);
}
};
function addNewAnnotation(polygon, color){
var newAnnotation = {
polygon: polygon || new Polygon(),
color: color || annotationColors[(self.annotations.length + 1) % annotationColors.length]
};
self.annotations.push(newAnnotation);
return newAnnotation;
}
function cleanupAnnotations(){
// delete all unclosed annotations
self.annotations = self.annotations.filter(function(annotation){
if(typeof annotation.polygon === 'object'
&& typeof annotation.polygon.isClosed !== 'undefined'){
return annotation.polygon.isClosed();
}
return false;
});
}
function getAnswerColor(){
var color = '#0000ff'; // Default: blue
// change color if answer is within solution
if(solutionVisible){ // show solution flag enabled?
var canvasAnswer = convertToCanvasTranslation(self.answer);
// is the answer within the solution?
if(self.solution !== null
&& self.solution.isWithinBounds(canvasAnswer.x, canvasAnswer.y)){
color = '#00ff00'; //green
} else {
color = '#ff0000'; // red
}
}
return color;
}
function drawAnswer(ctx){
// preserve context
ctx.save();
var shapeScale = 1.5
, transalation = convertToCanvasTranslation(self.answer);
ctx.translate(transalation.x, transalation.y);
ctx.scale(shapeScale * scale, shapeScale * scale);
ctx.shadowColor = '#ffffff';
ctx.shadowBlur = 5;
drawAwesomeIcon(ctx, '\uf05b', getAnswerColor(), 0, 0, 50);
// restore context
ctx.restore();
}
function getUIElements(){
var collectedUIElements = [];
// add buttons
collectedUIElements = collectedUIElements.concat(buttons).concat(colorButtons);
// only add the polygon vertices handler
// if there is an active polygon
// and we are in polygon edit mode
// (and add them before the polygons)
if((solutionEditable || annotationsEditable) && activePolygon !== null){
collectedUIElements = collectedUIElements.concat(activePolygon.getVertices());
}
// add annotations
collectedUIElements = collectedUIElements.concat(self.annotations.map(function(annotation){
return annotation.polygon;
}));
// add solution, if it exists
if(self.solution !== null) collectedUIElements.push(self.solution);
return collectedUIElements;
}
function getUIElement(evt){
var rect = canvas.getBoundingClientRect()
, pos = {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
}
, activeUIElement =
getUIElements()
.filter(function(uiElement){
return uiElement.isWithinBounds(pos.x, pos.y);
});
return (activeUIElement.length > 0 ) ? activeUIElement[0] : null;
}
function onMouseDown(evt){
if(evt.button === 0){ // left/main button
var activeElement = getUIElement(evt);
if(activeElement === null || !activeElement.onMouseDown(evt)){
// set flag for image moving
leftMouseButtonDown = true;
}
}
}
function onMouseUp(evt){
if(evt.button === 0){ // left/main button
activeMoveElement = centre;
leftMouseButtonDown = false;
}
}
function onMouseClick(evt){
if(evt.button === 0){ // left/main button
var activeElement = getUIElement(evt);
if(activeElement === null || activeElement.onClick(evt)){
var rect = canvas.getBoundingClientRect()
, clickPos = {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
if(isState('ANSWER_DRAW')){
self.answer = convertToImagePosition(clickPos);
dirty = true;
}
else if(isState('POLYGON_DRAW')){
if(evt.shiftKey){
// close polygon
if(activePolygon !== null){
activePolygon.close();
state = states.DEFAULT;
if(activePolygon === self.solution){
self.onSolutionChange(self.exportSolution());
} else {
cleanupAnnotations();
self.onAnnotationChange(self.exportAnnotations());
}
}
} else {
var newVertexPosition = convertToImagePosition(clickPos)
, newVertex = createVertex(newVertexPosition.x, newVertexPosition.y);
if(activePolygon === null){
if(solutionEditable){
if(self.solution === null){
self.solution = new Polygon();
}
activePolygon = self.solution;
} else if(annotationsEditable){
console.log("No active polygon. Click on a polygon to edit it!");
return;
} else {
console.log("invalid POLYGON_DRAW state");
return;
}
}
activePolygon.addVertex(newVertex);
}
dirty = true;
}
else {
if(activePolygon !== null){
activePolygon = null;
dirty = true;
}
}
}
}
}
function onMouseWheel(evt){
if (!evt) evt = event;
evt.preventDefault();
if(evt.detail < 0 || evt.wheelDelta > 0){ // up -> smaller
self.zoomOut();
} else { // down -> larger
self.zoomIn();
}
}
function onMouseMove(evt){
var rect = canvas.getBoundingClientRect()
, newPos = {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
mouseLastPos = mouseLastPos || { x: 0, y: 0 };
var deltaX = newPos.x - mouseLastPos.x
, deltaY = newPos.y - mouseLastPos.y;
if(leftMouseButtonDown){
if(activeMoveElement === centre){
activeMoveElement.x -= deltaX / scale;
activeMoveElement.y -= deltaY / scale;
} else {
activeMoveElement.x += deltaX / scale;
activeMoveElement.y += deltaY / scale;
if(activePolygon === self.solution){
self.onSolutionChange(self.exportSolution());
} else {
cleanupAnnotations();
self.onAnnotationChange(self.exportAnnotations());
}
}
dirty = true;
} else {
var activeElement = getUIElement(evt)
, oldToolTip = currentTooltip;
if(activeElement !== null){
if(typeof activeElement.tooltip !== 'undefined'){
currentTooltip = activeElement.tooltip;
}
// new focus UI element?
if(activeElement !== focusUIElement){
focusUIElement = activeElement;
}
} else { // no activeElement
currentTooltip = null;
if(focusUIElement !== null){
focusUIElement = null;
}
}
if(oldToolTip !== currentTooltip) dirty = true;
}
mouseLastPos = newPos;
if(solutionEditable || annotationsEditable) dirty = true;
}
function Button(icon, tooltip){
// drawn on position
this.drawPosition = null;
this.drawRadius = 0;
// transparency
this.alpha = 0.5;
// border
this.lineWidth = 0; // default: 0 == disabled
this.strokeStyle = '#000000';
// color
this.color = '#000000';
// icon unicode from awesome font
this.icon = icon;
this.iconColor = '#ffffff';