-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
1334 lines (1031 loc) · 46.1 KB
/
main.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
// easyAnnotate JavaScript.
// define a 'constant' so we can easily select video, no matter what we choose to call it in final HTML implementation...
var VIDEO_SELECTOR = 'video';
var VIDEO_PLAYER_ELEMENT = document.getElementById('videoPlayer');
var VIDEO_CONTAINER = 'div#vid-overlay';
var ANNOTATION_PANE = '#vidAnnotation';
var ANNOTATIONS_ON_SCREEN_SELECTOR = 'div.annotation-on-screen';
// and a 'constant' to select our add button...
var ADD_BUTTON_SELECTOR = 'a#addAnnotation';
var REMOVE_BUTTON_SELECTOR = 'a.removeAnnotation';
var PLAY_PAUSE_SELECTOR = 'a#playPauseButton';
var PROGRESS_BAR_SELECTOR = 'progress#progress';
var INFORMATION_TEXT_SELECTOR = 'div#informationalText';
var VOLUME_DOWN_SELECTOR = 'a#volume-down';
var VOLUME_UP_SELECTOR = 'a#volume-up';
var HIDEY_SHOW_BUTTON = 'a#hidey-showy';
var CLEAR_ALL_BUTTON = 'a#delete-everything-button';
var TOGGLE_ANNOTATIONS_BUTTON = 'a#toggle-annotations-button';
var RUNNING_TIME = 'span#play-time';
var ANNOTATION_FORM_SELECTOR = '#addAnnotationForm';
var FORM_SAVE_BUTTON = 'a#saveAddForm';
var FORM_CANCEL_BUTTON = 'a#cancelAddForm';
var FORM_TEXT_FIELD = '#form-annotation-text';
var FORM_LENGTH_FIELD = '#form-annotation-length';
var FORM_LINK_FIELD = '#form-annotation-link';
var CANVAS_SELECTOR = 'canvas';
var CHANGE_VIDEO_FORM_SELECTOR = 'form#videoURL';
var CHANGE_VIDEO_BUTTON = 'a#change-video-button';
var VIDEO_URL_BUTTON = '#videoURLSubmit';
var FORM_VIDEO_URL_FIELD = '#form-video-URL';
var FORM_IMAGE_URL_FIELD = '#form-image-url';
var TEXT_TAB_LINK = '#textTab';
var IMAGE_TAB_LINK = '#imageTab';
var TEXT_TAB_CONTENT = '#textTabContent';
var IMAGE_TAB_CONTENT = '#imageTabContent';
var FORM_IMAGE_WHITESPACE = '#form-remove-image-whitespace';
var FORM_TEXT_WHITESPACE = '#form-remove-text-whitespace';
var COLOUR_BUTTON = "#background-colour-button";
var TEXT_COLOUR_BUTTON = "#text-colour-button";
var DEFAULT_ANNOTATION_COLOUR = "rgba(89, 124, 86, 0.7)";
var DEFAULT_TEXT_COLOUR = "rgba(255, 255, 255, 1.0)";
var DEFAULT_VID_WIDTH = 400;
var DEFAULT_VID_HEIGHT = 220;
var LARGE_VID_WIDTH = 600;
var LARGE_VID_HEIGHT = 330;
var VID_WIDTH_TO_HEIGHT_MULTIPLIER = 0.55;
//Fun fact: 1.5 is the least metal number.
var ANTI_ROC_SOC_CONSTANT = 1.5;
//canvas variables
var canvas = document.getElementById('vid-canvas');
var ctx = canvas.getContext('2d');
//variable storing width of video currently
var vidWidth = DEFAULT_VID_WIDTH; //video starts at 400px wide
//variable storing height of video currently
var vidHeight = DEFAULT_VID_HEIGHT; //video starts at 220px high
//rect is a dictionary which will contain an x, y, width and height.
var rect = {};
//booleans to tell the canvas whether or not it is currently drawing boxes, and whether or not it is allowed to.
var dragging = false;
var canDraw = false;
// global variables
// number of whole seconds that the video's been playing for.
var currentTime = 0;
// an array that holds annotation objects.
var annotationsArray = [];
//is the player large at the moment? (starts off small...)
var isPlayerLarge = false;
//is the annotation button visible (no by default)
var isAnnotationFormVisible = false;
//should we even bother displaying annotations!? :o
var shouldDisplayAnnotations = true;
//z-index for annotation counter (newer annotations have priority, counter)
var zIndex = 3000; //starts at 3000
//if we're skipping via the progress bar, we wanna add *all* possible annotations to screen during the next call of update...
var isSkipping = false;
//default tab is text
var tab = 1;
//default font size is 16
var fontSize = 16;
// annotation object prototype.
function Annotation(text, imageUrl, xPosition, yPosition, width, height, startTime, endTime, zIndex, backgroundColour, textColour, link) {
this.textString = text;
this.imageUrl = imageUrl;
this.xPosition = xPosition;
this.yPosition = yPosition;
this.aWidth = width;
this.aHeight = height;
this.startTime = startTime;
this.endTime = endTime;
this.zIndex = zIndex;
this.backgroundColour = backgroundColour;
this.textColour = textColour;
this.link = link;
}
//create an md5 hash consisting of the annotation's start time, end time, x, y, and text....
function uniqueIdForAnnotation(a) {
//concatenate our huge string of annotation stuff...
var stringToMakeUnique = (String(a.startTime)) + (String(a.endTime)) + (String(a.xPosition)) + (String(a.yPosition)) + (String(a.text));
//make a hash using the crypto-js MD5 library
var hash = CryptoJS.MD5(stringToMakeUnique);
//make sure it's in string form, then return it
return hash.toString();
}
function testAnnotation(name) {
var newAnnotation = new Annotation(name, null, 30, 30, 30, 30, 3, 5, 3000, DEFAULT_ANNOTATION_COLOUR, DEFAULT_TEXT_COLOUR, null);
annotationsArray.push(newAnnotation);
console.log(annotationsArray);
}
function addAnnotationToScreen(a) {
//see if we should even be displaying annotations...
if (!shouldDisplayAnnotations) {
//we shouldn't be showing anything - give up and go home...
return;
}
//get a unique id first...
var id = uniqueIdForAnnotation(a);
var annotationLink = '';
if (a.link != null && a.link.length > 0) {
annotationLink = a.link;
}
//create our annotation html...
var annotationHtmlElement = '<div class="annotation-on-screen" data-easyannotation-annotation-href="' + annotationLink + '" title="' + annotationLink + '" id="' + id + '"></div>';
//work out the current annotation's selector so we can select and set attributes in jQuery
var annotationSelector = 'div#' + id;
//add it to the DOM so we can begin to add style etc...
$(VIDEO_CONTAINER).append(annotationHtmlElement);
console.log('attempting to add:' + annotationHtmlElement);
var height = a.aHeight;
//perform a 'lil bounds checking, we don't want stupidly small annotations...
if (height < 20) {
height = 20;
}
var width = a.aWidth;
//perform a 'lil bounds checking, we don't want stupidly small annotations...
if (width < 30) {
width = 30;
}
width = (width * vidWidth / DEFAULT_VID_WIDTH);
height = (height * vidWidth / DEFAULT_VID_WIDTH);
var x = (a.xPosition * vidWidth / DEFAULT_VID_WIDTH);
var y = (a.yPosition * vidWidth / DEFAULT_VID_WIDTH);
//we don't want annotations to end up bigger than the player...
var maxHeight = ((vidWidth * VID_WIDTH_TO_HEIGHT_MULTIPLIER) - y);
var maxWidth = (vidWidth - x);
//try the default colour...
var annotationColour = DEFAULT_ANNOTATION_COLOUR;
//if the annotation has a colour associated with it, use it instead...
if (a.backgroundColour) {
annotationColour = a.backgroundColour;
}
//see if there's a text colour...
var textColour = DEFAULT_TEXT_COLOUR;
if (textColour != null) {
textColour = a.textColour;
}
//set height and width, and a high z-index so it shows over the video.
$(annotationSelector).css({
"width": width,
"height": height,
"position": "absolute",
"padding": "5px",
"overflow": "auto",
"top": y,
"left": x,
"max-width": maxWidth,
"max-height": maxHeight,
"z-index": a.zIndex,
"background-color": annotationColour,
"color": textColour
});
//add the no-select class - selecting annotation text does not look pro
$(annotationSelector).addClass('no-select');
var annotationString = a.textString;
console.log('annotation title: ' + annotationString);
if (annotationString == null) {
annotationString = "";
}
annotationString = '<p>' + annotationString + '</p>';
$(annotationSelector).html(annotationString);
//if there's an image, add it...
if (a.imageUrl != null) {
//create an image tag...
var imageElement = '<img src="' + a.imageUrl + '"/>';
//add blank image into the annotation...
$(annotationSelector).append(imageElement);
var imageSelector = annotationSelector + ' img';
//do a 'lil styling
$(imageSelector).css({"width": "100%", "height": "auto"});
}
}
function removeAnnotationFromScreen(a) {
//get a unique id first...
var id = uniqueIdForAnnotation(a);
//work out the current annotation's selector so we can select and remove it from screen
var annotationSelector = 'div#' + id;
//remove...
$(annotationSelector).remove();
}
// the update method, to be called every time the running time of the video changes by a whole second
function update() {
console.log('update called.');
//update running time...
$(RUNNING_TIME).text(formatSecondsToString(currentTime));
//if we're skipping via the progress bar, we want to remove everything, add all possible annotations on screen
//and then set the skip variable to no, and return.
if (isSkipping) {
//remove any annotations currently on screen - correct ones are gonna be re-drawn next...
$(ANNOTATIONS_ON_SCREEN_SELECTOR).remove();
//draw any annotations on screen that should be on at this second (regardless of whether or not it's their exact start time)
putAllCurrentAnnotationsOnScreen();
//set the skipping variable to false so that this doesn't happen every time!
isSkipping = false;
//and return, so as not to draw stuff twice...
return;
}
// we want annotations that have a start time greater than or equal to the current playback time,
// but also an end time less than the current time.
// some funky jquery to search through the array.
var currentAnnotations = $.grep(annotationsArray, function (e) {
return (currentTime >= e.startTime && currentTime < e.endTime);
});
// these things might also be useful to know I guess...
// get annotations that need to be added (i.e. have a start time of the current second)
var newAnnotations = $.grep(annotationsArray, function (e) {
return (currentTime == e.startTime);
});
if (newAnnotations != null) {
if (newAnnotations.length > 0) {
//there's animations to load!
console.log('have new annotations to load');
for (var i = 0; i < newAnnotations.length; i++) {
//make a new annotation div, set it's id tag to the unique ID for this particular annotation
//add all of the relevant attributes from the annotation, then add it to the video player...
console.log('need to add something.');
var newAnnotation = newAnnotations[i];
console.log(newAnnotation);
addAnnotationToScreen(newAnnotation);
}
}
}
// and get annotations that need to be removed (i.e. have an end time of the current second)
var oldAnnotations = $.grep(annotationsArray, function (e) {
return (currentTime == e.endTime);
});
if (oldAnnotations != null) {
if (oldAnnotations.length > 0) {
//there's animations to remove!
console.log('have old annotations to remove');
for (var i = 0; i < oldAnnotations.length; i++) {
//work out its unique ID, then remove it from the document (taking it off screen)
console.log('need to remove something.');
removeAnnotationFromScreen(oldAnnotations[i]);
}
}
}
console.log(currentAnnotations);
}
//a function to add ANY annotations that should be on screen at the current time to the screen -
//regardless of whether their current start time is *now*...
//be careful when calling this - with great power comes great responsibility, etc.
function putAllCurrentAnnotationsOnScreen() {
//find everything that should potentially be on screen...
// some funky jquery to search through the array.
var currentAnnotations = $.grep(annotationsArray, function (e) {
return (currentTime >= e.startTime && currentTime < e.endTime);
});
if (currentAnnotations != null) {
if (currentAnnotations.length > 0) {
//there's animations to load!
console.log('have new annotations to load');
for (var i = 0; i < currentAnnotations.length; i++) {
//make a new annotation div, set it's id tag to the unique ID for this particular annotation
//add all of the relevant attributes from the annotation, then add it to the video player...
console.log('need to add something.');
var newAnnotation = currentAnnotations[i];
console.log(newAnnotation);
addAnnotationToScreen(newAnnotation);
}
}
}
}
// perform some basic setup tasks such as loading in the existing array of annotations from local storage...
function setUp() {
//see if we have a saved video URL in local storage...
if (localStorage.getItem('easyannotate-video-url')) {
//if we do, set our player to use it...
var videoURL = localStorage.getItem('easyannotate-video-url');
$(VIDEO_PLAYER_ELEMENT).find('#MP4-video').attr('src', videoURL);
$(VIDEO_PLAYER_ELEMENT).bind("loadedmetadata", function () {
var width = this.videoWidth;
var height = this.videoHeight;
console.log(width);
console.log(height);
if ((width / height) > 1.818) {
//width is the problem in this case, so set the newWidth to vidWidth
$(VIDEO_PLAYER_ELEMENT).width(vidWidth);
}
else { //height is the problem in this case (or it's perfect), so set the newHeight to vidHeight
$(VIDEO_PLAYER_ELEMENT).height(vidHeight);
}
});
//load into the player
VIDEO_PLAYER_ELEMENT.load();
//reset play time to 0 seconds...
VIDEO_PLAYER_ELEMENT.currentTime = 0;
}
//see if there's a saved unique video ID in local storage...
//set the video unique element id to videoElementID
if (localStorage.getItem('easyannotate-video-id')) {
var videoElementID = localStorage.getItem('easyannotate-video-id');
$(VIDEO_PLAYER_ELEMENT).attr('data-easyannotation-file-id', videoElementID);
}
//data-easyannotation-file-id is the attribute that holds our local storage file id, get it...
var localStorageId = $(VIDEO_SELECTOR).attr('data-easyannotation-file-id');
console.log(localStorageId);
//check there's actually something to load in first...
if (localStorage.getItem(localStorageId)) {
//go ahead and load...
//load in from local storage...
var localData = JSON.parse(localStorage.getItem(localStorageId));
//if the array is null, then set our array of annotations to a blank array (so we're not having null pointer issues)
//otherwise, set it to the parsed array we've retrieved from local storage (stored in localData currently...)
if (localData == null) {
// there's no saved data to load in, use a blank array...
annotationsArray = [];
} else {
// there's actually data to load in :o
// let's load it...
annotationsArray = localData;
}
} else {
//no saved data :'(
//let's make annotationsArray a blank array object then...
annotationsArray = [];
}
// Daniel's madness :O
// Remove the default browser controls
$(VIDEO_SELECTOR).controls = false;
//sort the array so earlier annotations come first...
annotationsArray.sort(function (a, b) {
return a.startTime - b.startTime;
});
//populate the annotations list...
populateAnnotationsList();
initCanvas();
}
// a convenience save function... we'll wanna call this after every edit, etc.
function saveAnnotations() {
//firstly, let's convert the array to a JSON string...
var jsonArray = JSON.stringify(annotationsArray);
//now, get the relevant local storage ID from the html data attribute...
var localStorageId = $(VIDEO_SELECTOR).data('easyannotation-file-id');
//save the converted data into the local storage of the browser, with the proper ID...
localStorage.setItem(localStorageId, jsonArray);
}
//clear just the current video's annotations from local storage...
function clearStoredAnnotations() {
//get the relevant local storage ID from the html data attribute...
var localStorageId = $(VIDEO_SELECTOR).data('easyannotation-file-id');
//save null...
localStorage.setItem(localStorageId, null);
//re-set local list variable...
annotationsArray = [];
}
//clear the contents of existing local storage items (probably just for testing purposes but you never know...)
function clearAllStoredAnnotations() {
//clear all local storage items associated with this page.
window.localStorage.clear();
//also, clear the current annotations array, setting it to a blank array object.
annotationsArray = [];
//confirm on the console, since this'll probably be used for debugging/testing
console.log('Local storage cleared.');
}
function addAnnotationClicked() {
//we really don't want multiple adds to happen at once...
//hide the button just in case...
$(ADD_BUTTON_SELECTOR).fadeTo("fast", 0);
$(CANVAS_SELECTOR).css('z-index', 5000);
//allow drawing to start and bring up an info dialog...
canDraw = true;
console.log('Starting to add annotation...');
//okay, first pause the video...
$(VIDEO_SELECTOR).trigger('pause');
//tell the user...
$(INFORMATION_TEXT_SELECTOR).text("Begin drawing over the video...(press escape to exit)");
}
function newAnnotationDrawingComplete() {
//clear the canvas...
ctx.clearRect(0, 0, canvas.width, canvas.height);
//the user isn't allowed to draw anymore...
canDraw = false;
//reset informational text...
$(INFORMATION_TEXT_SELECTOR).text("");
//show the add annotation form...
toggleAddAnnotationForm();
$(CANVAS_SELECTOR).css('z-index', 2000);
}
function saveAnnotationButtonClicked() {
//not so freakin' basic.
//get a title from our fanciful form.
var title = $(FORM_TEXT_FIELD).val();
//get the what the form links to
var link = $(FORM_LINK_FIELD).val();
if (link != null && link.length > 0) {
if (isValidUrl(link) || link.length < 4) {
// LINK IS VALID!
console.log('valid link: ' + link);
} else {
//INVALID!
//warn user, give up, go home.
alert('Invalid link URL! Please check and try again...');
return;
}
} else {
link = null;
}
//get how long the annotation should run for
var time = $(FORM_LENGTH_FIELD).val();
//see if it's an image annotation?
var imageUrl = $(FORM_IMAGE_URL_FIELD).val();
//see if whitespace boxes are clicked?
var imageWhitespace = $(FORM_IMAGE_WHITESPACE).val();
console.log(imageWhitespace);
var textWhitespace = $(FORM_TEXT_WHITESPACE).val();
//if there's something there, validate it...
if (imageUrl != null && imageUrl.length > 0) {
if (isValidUrl(imageUrl) || imageUrl.length < 4) {
//it's valid
//make title nothing... (1 blank char. to pass validation later on!)
title = ' ';
} else {
//INVALID!
//warn user, give up, go home.
alert('Invalid image URL! Please check and try again...');
return;
}
} else {
imageUrl = null;
}
//and allow the adding of more annotations...
$(ADD_BUTTON_SELECTOR).fadeTo("fast", 1);
//close the form...
toggleAddAnnotationForm();
//clear form values back to the default...
resetFormValues();
//if the time entered isn't an integer set the time to 2 seconds
if (time == null || isNaN(time)) {
time = "2";
}
//get x and y and width + height that has been drawn previously by the user...
var drawnX = rect.startX;
var drawnY = rect.startY;
var drawnWidth = rect.w;
var drawnHeight = rect.h;
//if the player's currently large, then the values need adjusting to fit the smaller player.
if (isPlayerLarge) { //adjust the values to fit the smaller video size
drawnX = (drawnX / ANTI_ROC_SOC_CONSTANT);
drawnY = (drawnY / ANTI_ROC_SOC_CONSTANT);
drawnWidth = (drawnWidth / ANTI_ROC_SOC_CONSTANT);
drawnHeight = (drawnHeight / ANTI_ROC_SOC_CONSTANT);
}
//do some minimum checking, we don't want the drawn rect to be too ridiculously small so an annotation can't physically fit...
if (drawnHeight < 20) {
drawnHeight = 20;
}
if (drawnWidth < 30) {
drawnWidth = 30;
}
if (imageWhitespace == 'on') {
//user wants the annotation to only be as big as the image/text
console.log('height set to auto as user wanted fitting annotation');
drawnHeight = 'auto';
}
else{
console.log('height not changed, user wanted whitespace');
}
//ensure that annotations can't be outside the video
if (drawnX + drawnWidth > (DEFAULT_VID_WIDTH - 10)) {
drawnX = 390 - drawnWidth;
}
if (drawnY + drawnHeight > ((DEFAULT_VID_WIDTH * VID_WIDTH_TO_HEIGHT_MULTIPLIER) - 10)) {
drawnY = 210 - drawnHeight;
}
//get a background colour from the colour picker element...
var backgroundColor = $(COLOUR_BUTTON).css("background-color");
//try and get a text colour too...
var textColour = $(TEXT_COLOUR_BUTTON).css("background-color");
//check that there's a proper title, and if so, go ahead adding the annotation...
if (title != null && title.length > 0) {
//create a new annotation with the variables we've got
var newAnnotation = new Annotation(title, imageUrl, drawnX, drawnY, drawnWidth, drawnHeight, currentTime, (currentTime + parseInt(time)), zIndex, backgroundColor, textColour, link);
//add the new annotation that we've created into the array...
annotationsArray.push(newAnnotation);
//let's save too!
saveAnnotations();
//and re-populate the list...
populateAnnotationsList();
//and increase zIndex
zIndex = zIndex + 1;
} else {
//the user hasn't entered a title - show an error!
alert("An annotation title is required - please enter one.");
}
}
function updateVideoURLClicked() {
//get the url from the form
var videoURL = $(FORM_VIDEO_URL_FIELD).val();
//check it's a accurate URL
if (!isValidUrl(videoURL)) {
//don't do anything because the video URL isn't correct
//alert the user...
alert("It looks like you've entered an invalid video URL... please check it over then try again.");
//then give up...
return false;
}
//get a unique hash for that particular video's video id based upon the URL...
var videoElementID = CryptoJS.MD5(videoURL);
//close the update form - we're happy with the url and we're gonna update...
toggleChangeVideoForm();
//save the new video URL into local storage...
localStorage.setItem('easyannotate-video-url', videoURL);
//and save the easyAnnotate ID into local storage...
localStorage.setItem('easyannotate-video-id', videoElementID);
//reset annotation list...
annotationsArray = [];
populateAnnotationsList();
//in the setup method, we attempt to load a video/video URL from local storage...
setUp();
console.log(videoURL);
}
function resetFormValues() {
//and clear the old values to defaults so new annotations don't have set ones...
$(FORM_TEXT_FIELD).val("");
$(FORM_LINK_FIELD).val("");
$(FORM_IMAGE_URL_FIELD).val("");
$(FORM_LENGTH_FIELD).val("2");
}
function cancelAnnotationFormButtonClicked() {
//give up and go home.
//close the form...
toggleAddAnnotationForm();
//and clear the old values to defaults so new annotations don't have set ones...
resetFormValues();
//and allow the adding of more annotations...
$(ADD_BUTTON_SELECTOR).fadeTo("fast", 1);
}
// **Control Stuff**
function playPauseClicked() {
if (VIDEO_PLAYER_ELEMENT.paused || VIDEO_PLAYER_ELEMENT.ended) {
VIDEO_PLAYER_ELEMENT.play();
$(PLAY_PAUSE_SELECTOR).html('<i class="fa fa-pause"></i>');
}
else {
VIDEO_PLAYER_ELEMENT.pause();
$(PLAY_PAUSE_SELECTOR).html('<i class="fa fa-play"></i>');
}
}
function formatSecondsToString(numberOfSeconds) {
var wholeMinutes = Math.floor(numberOfSeconds / 60);
var secondsRemaining = numberOfSeconds - (wholeMinutes * 60);
if (secondsRemaining < 10) {
//if it's under 10 seconds, make it "0:01" not "0:1"
secondsRemaining = "0" + String(secondsRemaining);
}
if (numberOfSeconds < 10) {
//if it's under 10 seconds, just return it...
return "0:0" + String(numberOfSeconds);
}
if (numberOfSeconds < 60) {
//if it's under a minute, just return it...
return "0:" + String(numberOfSeconds);
}
return String(wholeMinutes) + ":" + String(secondsRemaining);
}
function updateProgressBar() {
var bar = document.getElementById('progress');
var percent = Math.floor((100 / VIDEO_PLAYER_ELEMENT.duration) * (VIDEO_PLAYER_ELEMENT.currentTime));
bar.value = percent;
bar.innerHTML = percent + "%";
}
//the following function's regex was from http://stackoverflow.com/questions/2723140/validating-url-with-jquery-without-the-validate-plugin
function isValidUrl(url) {
//ugly ugly regex checking provided by http://stackoverflow.com/questions/2723140/validating-url-with-jquery-without-the-validate-plugin
return !!/^([a-z]([a-z]|\d|\+|-|\.)*):(\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?((\[(|(v[\da-f]{1,}\.(([a-z]|\d|-|\.|_|~)|[!\$&'\(\)\*\+,;=]|:)+))\])|((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=])*)(:\d*)?)(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*|(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)|((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)|((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)){0})(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(url);
}
function populateAnnotationsList() {
//sort the array so earlier annotations come first...
annotationsArray.sort(function (a, b) {
return a.startTime - b.startTime;
});
//clear any existing annotations in the list...
$("li.vidAnnotationListItem").each(function () {
//remove it!
this.remove();
});
//loop through the array, adding a new li element in the appropriate list for each one...
for (var i = 0; i < annotationsArray.length; i++) {
//get the current list item...
var currentAnnotation = annotationsArray[i];
//assume it's a text annotation...
var annotationTypeString = 'Text annotation';
//check to see if it's a fancy image one?
var imageElement = '';
if (currentAnnotation.imageUrl != null) {
//okay there's an image url... it's actually an image annotation...
annotationTypeString = 'Image annotation';
//create an image tag...
imageElement = '<img style="width: 100%; height: auto; margin-top: 5px;" src="' + currentAnnotation.imageUrl + '"/>';
}
var linkText = '';
var linkFormatted = '';
console.log(currentAnnotation.link);
if (currentAnnotation.link != null) {
if (currentAnnotation.link.length > 35) {
linkFormatted = currentAnnotation.link.substring(0, 32) + "...";
}
else {
linkFormatted = currentAnnotation.link;
}
linkText = '<div class="annotationLink" title="' + currentAnnotation.link + '"><a href="' + currentAnnotation.link + '" target="_blank"><i class="fa fa-link"></i> ' + linkFormatted + '</a></div>';
}
console.log(linkText);
//formulate our new li HTML...
var newListElement = '<li class="vidAnnotationListItem" style="background-color: ' + currentAnnotation.backgroundColour + ';" ><a class="removeAnnotation" href="#" data-easyannotation-annotation-id="' + i + '">X</a><div class="vidAnnotationType">' + annotationTypeString + '</div><div class="vidAnnotationTimes">' + formatSecondsToString(currentAnnotation.startTime) + ' - ' + formatSecondsToString(currentAnnotation.endTime) + '</div><div class="vidAnnotationContent" style="color: ' + currentAnnotation.textColour + ';">' + imageElement + currentAnnotation.textString + '</div>' + linkText + '</li>';
//and add it to the end of the list...
$("ul#vidAnnotationList").append(newListElement);
}
//if there are some annotations, remove the background image that claims there aren't!
if (annotationsArray.length > 0) {
//there's annotations - make it so...
$(ANNOTATION_PANE).css({'background-image': "none"});
} else {
//there's no annotations - use the pretty placeholder...
$(ANNOTATION_PANE).css({'background-image': "url('resources/noAnnotations.png')"});
}
}
function deleteAnnotationAtIndex(index) {
//if the annotation happens to be on screen, try to remove it first...
var annotation = annotationsArray[index];
//remove swiftly and mercilessly (if we can)
removeAnnotationFromScreen(annotation);
//remove 1 item, at the current index, from the annotations array...
annotationsArray.splice(index, 1);
//redraw the list...
populateAnnotationsList();
//we've modified the array so save it...
saveAnnotations();
}
//crude mouse fix from http://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
//canvas drawing stuff...
//(quite a lot of this canvas stuff is shamefully stolen from http://atomicrobotdesign.com/blog/javascript/draw-a-rectangle-using-the-mouse-on-the-canvas-in-less-than-40-lines-of-javascript/)
function initCanvas() {
canvas.addEventListener('mousedown', mouseDownCanvas, false);
canvas.addEventListener('mouseup', mouseUpCanvas, false);
canvas.addEventListener('mousemove', mouseMoveCanvas, false);
}
function mouseDownCanvas(e) {
//the user wants to begin drawing, if they're allowed, then begin
if (canDraw) {
rect.startX = getMousePos(canvas, e).x;
rect.startY = getMousePos(canvas, e).y;
console.log(rect);
dragging = true;
}
}
function mouseUpCanvas() {
//if we're not supposed to be creating annotations at the moment, don't allow it - just give up...
if (!canDraw) {
return;
}
dragging = false;
//drawing complete!!!!!1
newAnnotationDrawingComplete();
}
function mouseMoveCanvas(e) {
if (dragging && canDraw) {
console.log('pageX: ' + e.pageX + ' pageY: ' + e.pageY);
rect.w = getMousePos(canvas, e).x - rect.startX;
rect.h = getMousePos(canvas, e).y - rect.startY;
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawCanvas();
}
}
function drawCanvas() {
if (canDraw) {
//set the fill colour
ctx.fillStyle = DEFAULT_ANNOTATION_COLOUR;
//and fill it in...
ctx.fillRect(rect.startX, rect.startY, rect.w, rect.h);
}
}
function toggleAddAnnotationForm() {
if (isAnnotationFormVisible) { //form currently visible, let's hide that
$(ANNOTATION_FORM_SELECTOR).hide();
$('#vidTitle').css('margin-top', '14px');
isAnnotationFormVisible = false; //since the form is now hidden
}
else { //form isn't visible, let's show it
$(ANNOTATION_FORM_SELECTOR).show();
$('#vidTitle').css('margin-top', '-200px');
//give it a default colour...
$(COLOUR_BUTTON).attr('value', DEFAULT_ANNOTATION_COLOUR);
$(TEXT_COLOUR_BUTTON).attr('value', DEFAULT_TEXT_COLOUR);
$(COLOUR_BUTTON).colorPicker(); // initialise colour picker
$(TEXT_COLOUR_BUTTON).colorPicker();
isAnnotationFormVisible = true; //since the form is now visible
}
}
function toggleChangeVideoForm() {
if ($(CHANGE_VIDEO_FORM_SELECTOR).is(":visible")) {
// hide it
$(CHANGE_VIDEO_FORM_SELECTOR).hide("fast");
} else {
//show it
$(CHANGE_VIDEO_FORM_SELECTOR).show("fast");
}
}
// jQuery events.
$(document).ready(function () {
//the DOM has loaded, so let's begin...
console.log('ready');
//set-up video (load in array of annotations...)
setUp();
//hide annotation form
$(ANNOTATION_FORM_SELECTOR).hide();
//hide image tab in annotation form
$(IMAGE_TAB_CONTENT).hide();
//hide change video form on load
$(CHANGE_VIDEO_FORM_SELECTOR).hide();
//super super handy reference for video tag info... http://www.w3schools.com/tags/ref_av_dom.asp
$(VIDEO_SELECTOR).bind('play', function () {
console.log('started playing.');
// NOTE: This is also called on resume from a pause, it's not unique to the video's first play.
// call update manually - there could be annotations that need to be shown at 0 secs!
update();
$(PLAY_PAUSE_SELECTOR).html('<i class="fa fa-pause"></i>');
});
$(VIDEO_SELECTOR).bind('pause', function () {
console.log('playback paused.');
$(PLAY_PAUSE_SELECTOR).html('<i class="fa fa-play"></i>');
});
$(VIDEO_SELECTOR).bind('ended', function () {
console.log('finished playing.');
// reset current time variable (but do not call update!)
currentTime = 0;
document.getElementById('progress').value = 0;
$(PLAY_PAUSE_SELECTOR).html('<i class="fa fa-play"></i>');
//remove any currently on screen annotations instantly
$(ANNOTATIONS_ON_SCREEN_SELECTOR).remove();
});
$(VIDEO_SELECTOR).bind('timeupdate', function () {
//update the progress bar no matter what...
updateProgressBar();
// the current video play time, in whole seconds (rounded down)
var newTime = Math.floor(this.currentTime);
// okay, we only care about updating if the time is different (in whole seconds)
// otherwise, the user's getting absolutely hammered with the DOM redrawing etc.
if (newTime != currentTime) {
// a whole second has passed (or many seconds if they video's been skipped)