-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcropper.js
3296 lines (2631 loc) · 85 KB
/
cropper.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
/*!
* Cropper v3.1.4
* https://github.com/fengyuanchen/cropper
*
* Copyright (c) 2014-2018 Chen Fengyuan
* Released under the MIT license
*
* Date: 2018-01-13T09:37:52.890Z
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('jquery')) :
typeof define === 'function' && define.amd ? define(['jquery'], factory) :
(factory(global.jQuery));
}(this, (function ($) { 'use strict';
$ = $ && $.hasOwnProperty('default') ? $['default'] : $;
var WINDOW = typeof window !== 'undefined' ? window : {};
var NAMESPACE = 'cropper';
// Actions
var ACTION_ALL = 'all';
var ACTION_CROP = 'crop';
var ACTION_MOVE = 'move';
var ACTION_ZOOM = 'zoom';
var ACTION_EAST = 'e';
var ACTION_WEST = 'w';
var ACTION_SOUTH = 's';
var ACTION_NORTH = 'n';
var ACTION_NORTH_EAST = 'ne';
var ACTION_NORTH_WEST = 'nw';
var ACTION_SOUTH_EAST = 'se';
var ACTION_SOUTH_WEST = 'sw';
// Classes
var CLASS_CROP = NAMESPACE + '-crop';
var CLASS_DISABLED = NAMESPACE + '-disabled';
var CLASS_HIDDEN = NAMESPACE + '-hidden';
var CLASS_HIDE = NAMESPACE + '-hide';
var CLASS_INVISIBLE = NAMESPACE + '-invisible';
var CLASS_MODAL = NAMESPACE + '-modal';
var CLASS_MOVE = NAMESPACE + '-move';
// Data keys
var DATA_ACTION = 'action';
var DATA_PREVIEW = 'preview';
// Drag modes
var DRAG_MODE_CROP = 'crop';
var DRAG_MODE_MOVE = 'move';
var DRAG_MODE_NONE = 'none';
// Events
var EVENT_CROP = 'crop';
var EVENT_CROP_END = 'cropend';
var EVENT_CROP_MOVE = 'cropmove';
var EVENT_CROP_START = 'cropstart';
var EVENT_DBLCLICK = 'dblclick';
var EVENT_ERROR = 'error';
var EVENT_LOAD = 'load';
var EVENT_POINTER_DOWN = WINDOW.PointerEvent ? 'pointerdown' : 'touchstart mousedown';
var EVENT_POINTER_MOVE = WINDOW.PointerEvent ? 'pointermove' : 'touchmove mousemove';
var EVENT_POINTER_UP = WINDOW.PointerEvent ? 'pointerup pointercancel' : 'touchend touchcancel mouseup';
var EVENT_READY = 'ready';
var EVENT_RESIZE = 'resize';
var EVENT_WHEEL = 'wheel mousewheel DOMMouseScroll';
var EVENT_ZOOM = 'zoom';
// RegExps
var REGEXP_ACTIONS = /^(e|w|s|n|se|sw|ne|nw|all|crop|move|zoom)$/;
var REGEXP_DATA_URL = /^data:/;
var REGEXP_DATA_URL_JPEG = /^data:image\/jpeg;base64,/;
var REGEXP_TAG_NAME = /^(img|canvas)$/i;
var DEFAULTS = {
// Define the view mode of the cropper
viewMode: 0, // 0, 1, 2, 3
// Define the dragging mode of the cropper
dragMode: DRAG_MODE_CROP, // 'crop', 'move' or 'none'
// Define the aspect ratio of the crop box
aspectRatio: NaN,
// An object with the previous cropping result data
data: null,
// A selector for adding extra containers to preview
preview: '',
// Re-render the cropper when resize the window
responsive: true,
// Restore the cropped area after resize the window
restore: true,
// Check if the current image is a cross-origin image
checkCrossOrigin: true,
// Check the current image's Exif Orientation information
checkOrientation: true,
// Show the black modal
modal: true,
// Show the dashed lines for guiding
guides: true,
// Show the center indicator for guiding
center: true,
// Show the white modal to highlight the crop box
highlight: true,
// Show the grid background
background: false,
// Enable to crop the image automatically when initialize
autoCrop: true,
// Define the percentage of automatic cropping area when initializes
autoCropArea: 0.8,
cropBox:[],
// Enable to move the image
movable: true,
// Enable to rotate the image
rotatable: true,
// Enable to scale the image
scalable: true,
// Enable to zoom the image
zoomable: true,
// Enable to zoom the image by dragging touch
zoomOnTouch: true,
// Enable to zoom the image by wheeling mouse
zoomOnWheel: true,
// Define zoom ratio when zoom the image by wheeling mouse
wheelZoomRatio: 0.1,
// Enable to move the crop box
cropBoxMovable: true,
// Enable to resize the crop box
cropBoxResizable: true,
// Toggle drag mode between "crop" and "move" when click twice on the cropper
toggleDragModeOnDblclick: true,
// Size limitation
minCanvasWidth: 0,
minCanvasHeight: 0,
minCropBoxWidth: 0,
minCropBoxHeight: 0,
minContainerWidth: 346,
minContainerHeight: 257,
// Shortcuts of events
ready: null,
cropstart: null,
cropmove: null,
cropend: null,
crop: null,
zoom: null
};
var TEMPLATE = '<div class="cropper-container">' + '<div class="cropper-wrap-box">' + '<div class="cropper-canvas"></div>' + '</div>' + '<div class="cropper-drag-box"></div>' + '<div class="cropper-crop-box">' + '<span class="cropper-view-box"></span>' + '<span class="cropper-dashed dashed-h"></span>' + '<span class="cropper-dashed dashed-v"></span>' + '<span class="cropper-center"></span>' + '<span class="cropper-face"></span>' + '<span class="cropper-line line-e" data-action="e"></span>' + '<span class="cropper-line line-n" data-action="n"></span>' + '<span class="cropper-line line-w" data-action="w"></span>' + '<span class="cropper-line line-s" data-action="s"></span>' + '<span class="cropper-point point-e" data-action="e"></span>' + '<span class="cropper-point point-n" data-action="n"></span>' + '<span class="cropper-point point-w" data-action="w"></span>' + '<span class="cropper-point point-s" data-action="s"></span>' + '<span class="cropper-point point-ne" data-action="ne"></span>' + '<span class="cropper-point point-nw" data-action="nw"></span>' + '<span class="cropper-point point-sw" data-action="sw"></span>' + '<span class="cropper-point point-se" data-action="se"></span>' + '</div>' + '</div>';
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
var createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
var toConsumableArray = function (arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
return arr2;
} else {
return Array.from(arr);
}
};
/**
* Check if the given value is a string.
* @param {*} value - The value to check.
* @returns {boolean} Returns `true` if the given value is a string, else `false`.
*/
function isString(value) {
return typeof value === 'string';
}
/**
* Check if the given value is not a number.
*/
var isNaN = Number.isNaN || WINDOW.isNaN;
/**
* Check if the given value is a number.
* @param {*} value - The value to check.
* @returns {boolean} Returns `true` if the given value is a number, else `false`.
*/
function isNumber(value) {
return typeof value === 'number' && !isNaN(value);
}
/**
* Check if the given value is undefined.
* @param {*} value - The value to check.
* @returns {boolean} Returns `true` if the given value is undefined, else `false`.
*/
function isUndefined(value) {
return typeof value === 'undefined';
}
/**
* Takes a function and returns a new one that will always have a particular context.
* Custom proxy to avoid jQuery's guid.
* @param {Function} fn - The target function.
* @param {Object} context - The new context for the function.
* @returns {Function} The new function.
*/
function proxy(fn, context) {
for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
args[_key - 2] = arguments[_key];
}
return function () {
for (var _len2 = arguments.length, args2 = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args2[_key2] = arguments[_key2];
}
return fn.apply(context, args.concat(args2));
};
}
/**
* Get the own enumerable properties of a given object.
* @param {Object} obj - The target object.
* @returns {Array} All the own enumerable properties of the given object.
*/
var objectKeys = Object.keys || function objectKeys(obj) {
var keys = [];
$.each(obj, function (key) {
keys.push(key);
});
return keys;
};
var REGEXP_DECIMALS = /\.\d*(?:0|9){12}\d*$/i;
/**
* Normalize decimal number.
* Check out {@link http://0.30000000000000004.com/ }
* @param {number} value - The value to normalize.
* @param {number} [times=100000000000] - The times for normalizing.
* @returns {number} Returns the normalized number.
*/
function normalizeDecimalNumber(value) {
var times = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 100000000000;
return REGEXP_DECIMALS.test(value) ? Math.round(value * times) / times : value;
}
var location = WINDOW.location;
var REGEXP_ORIGINS = /^(https?:)\/\/([^:/?#]+):?(\d*)/i;
/**
* Check if the given URL is a cross origin URL.
* @param {string} url - The target URL.
* @returns {boolean} Returns `true` if the given URL is a cross origin URL, else `false`.
*/
function isCrossOriginURL(url) {
var parts = url.match(REGEXP_ORIGINS);
return parts && (parts[1] !== location.protocol || parts[2] !== location.hostname || parts[3] !== location.port);
}
/**
* Add timestamp to the given URL.
* @param {string} url - The target URL.
* @returns {string} The result URL.
*/
function addTimestamp(url) {
var timestamp = 'timestamp=' + new Date().getTime();
return url + (url.indexOf('?') === -1 ? '?' : '&') + timestamp;
}
/**
* Get transform values base on the given object.
* @param {Object} obj - The target object.
* @returns {string} A string contains transform values.
*/
function getTransformValues(_ref) {
var rotate = _ref.rotate,
scaleX = _ref.scaleX,
scaleY = _ref.scaleY,
translateX = _ref.translateX,
translateY = _ref.translateY;
var values = [];
if (isNumber(translateX) && translateX !== 0) {
values.push('translateX(' + translateX + 'px)');
}
if (isNumber(translateY) && translateY !== 0) {
values.push('translateY(' + translateY + 'px)');
}
// Rotate should come first before scale to match orientation transform
if (isNumber(rotate) && rotate !== 0) {
values.push('rotate(' + rotate + 'deg)');
}
if (isNumber(scaleX) && scaleX !== 1) {
values.push('scaleX(' + scaleX + ')');
}
if (isNumber(scaleY) && scaleY !== 1) {
values.push('scaleY(' + scaleY + ')');
}
return values.length ? values.join(' ') : 'none';
}
var navigator = WINDOW.navigator;
var IS_SAFARI_OR_UIWEBVIEW = navigator && /(Macintosh|iPhone|iPod|iPad).*AppleWebKit/i.test(navigator.userAgent);
/**
* Get an image's natural sizes.
* @param {string} image - The target image.
* @param {Function} callback - The callback function.
*/
function getImageNaturalSizes(image, callback) {
// Modern browsers (except Safari)
if (image.naturalWidth && !IS_SAFARI_OR_UIWEBVIEW) {
callback(image.naturalWidth, image.naturalHeight);
return;
}
var newImage = document.createElement('img');
newImage.onload = function () {
callback(newImage.width, newImage.height);
};
newImage.src = image.src;
}
/**
* Get the max ratio of a group of pointers.
* @param {string} pointers - The target pointers.
* @returns {number} The result ratio.
*/
function getMaxZoomRatio(pointers) {
var pointers2 = $.extend({}, pointers);
var ratios = [];
$.each(pointers, function (pointerId, pointer) {
delete pointers2[pointerId];
$.each(pointers2, function (pointerId2, pointer2) {
var x1 = Math.abs(pointer.startX - pointer2.startX);
var y1 = Math.abs(pointer.startY - pointer2.startY);
var x2 = Math.abs(pointer.endX - pointer2.endX);
var y2 = Math.abs(pointer.endY - pointer2.endY);
var z1 = Math.sqrt(x1 * x1 + y1 * y1);
var z2 = Math.sqrt(x2 * x2 + y2 * y2);
var ratio = (z2 - z1) / z1;
ratios.push(ratio);
});
});
ratios.sort(function (a, b) {
return Math.abs(a) < Math.abs(b);
});
return ratios[0];
}
/**
* Get a pointer from an event object.
* @param {Object} event - The target event object.
* @param {boolean} endOnly - Indicates if only returns the end point coordinate or not.
* @returns {Object} The result pointer contains start and/or end point coordinates.
*/
function getPointer(_ref2, endOnly) {
var pageX = _ref2.pageX,
pageY = _ref2.pageY;
var end = {
endX: pageX,
endY: pageY
};
if (endOnly) {
return end;
}
return $.extend({
startX: pageX,
startY: pageY
}, end);
}
/**
* Get the center point coordinate of a group of pointers.
* @param {Object} pointers - The target pointers.
* @returns {Object} The center point coordinate.
*/
function getPointersCenter(pointers) {
var pageX = 0;
var pageY = 0;
var count = 0;
$.each(pointers, function (pointerId, _ref3) {
var startX = _ref3.startX,
startY = _ref3.startY;
pageX += startX;
pageY += startY;
count += 1;
});
pageX /= count;
pageY /= count;
return {
pageX: pageX,
pageY: pageY
};
}
/**
* Check if the given value is a finite number.
*/
var isFinite = Number.isFinite || WINDOW.isFinite;
/**
* Get the max sizes in a rectangle under the given aspect ratio.
* @param {Object} data - The original sizes.
* @returns {Object} The result sizes.
*/
function getContainSizes(_ref4) {
var aspectRatio = _ref4.aspectRatio,
height = _ref4.height,
width = _ref4.width;
var isValidNumber = function isValidNumber(value) {
return isFinite(value) && value > 0;
};
if (isValidNumber(width) && isValidNumber(height)) {
if (height * aspectRatio > width) {
height = width / aspectRatio;
} else {
width = height * aspectRatio;
}
} else if (isValidNumber(width)) {
height = width / aspectRatio;
} else if (isValidNumber(height)) {
width = height * aspectRatio;
}
return {
width: width,
height: height
};
}
/**
* Get the new sizes of a rectangle after rotated.
* @param {Object} data - The original sizes.
* @returns {Object} The result sizes.
*/
function getRotatedSizes(_ref5) {
var width = _ref5.width,
height = _ref5.height,
degree = _ref5.degree;
degree = Math.abs(degree) % 180;
if (degree === 90) {
return {
width: height,
height: width
};
}
var arc = degree % 90 * Math.PI / 180;
var sinArc = Math.sin(arc);
var cosArc = Math.cos(arc);
var newWidth = width * cosArc + height * sinArc;
var newHeight = width * sinArc + height * cosArc;
return degree > 90 ? {
width: newHeight,
height: newWidth
} : {
width: newWidth,
height: newHeight
};
}
/**
* Get a canvas which drew the given image.
* @param {HTMLImageElement} image - The image for drawing.
* @param {Object} imageData - The image data.
* @param {Object} canvasData - The canvas data.
* @param {Object} options - The options.
* @returns {HTMLCanvasElement} The result canvas.
*/
function getSourceCanvas(image, _ref6, _ref7, _ref8) {
var imageNaturalWidth = _ref6.naturalWidth,
imageNaturalHeight = _ref6.naturalHeight,
_ref6$rotate = _ref6.rotate,
rotate = _ref6$rotate === undefined ? 0 : _ref6$rotate,
_ref6$scaleX = _ref6.scaleX,
scaleX = _ref6$scaleX === undefined ? 1 : _ref6$scaleX,
_ref6$scaleY = _ref6.scaleY,
scaleY = _ref6$scaleY === undefined ? 1 : _ref6$scaleY;
var aspectRatio = _ref7.aspectRatio,
naturalWidth = _ref7.naturalWidth,
naturalHeight = _ref7.naturalHeight;
var _ref8$fillColor = _ref8.fillColor,
fillColor = _ref8$fillColor === undefined ? 'transparent' : _ref8$fillColor,
_ref8$imageSmoothingE = _ref8.imageSmoothingEnabled,
imageSmoothingEnabled = _ref8$imageSmoothingE === undefined ? true : _ref8$imageSmoothingE,
_ref8$imageSmoothingQ = _ref8.imageSmoothingQuality,
imageSmoothingQuality = _ref8$imageSmoothingQ === undefined ? 'low' : _ref8$imageSmoothingQ,
_ref8$maxWidth = _ref8.maxWidth,
maxWidth = _ref8$maxWidth === undefined ? Infinity : _ref8$maxWidth,
_ref8$maxHeight = _ref8.maxHeight,
maxHeight = _ref8$maxHeight === undefined ? Infinity : _ref8$maxHeight,
_ref8$minWidth = _ref8.minWidth,
minWidth = _ref8$minWidth === undefined ? 0 : _ref8$minWidth,
_ref8$minHeight = _ref8.minHeight,
minHeight = _ref8$minHeight === undefined ? 0 : _ref8$minHeight;
var maxSizes = getContainSizes({
aspectRatio: aspectRatio,
width: maxWidth,
height: maxHeight
});
var minSizes = getContainSizes({
aspectRatio: aspectRatio,
width: minWidth,
height: minHeight
});
var width = Math.min(maxSizes.width, Math.max(minSizes.width, naturalWidth));
var height = Math.min(maxSizes.height, Math.max(minSizes.height, naturalHeight));
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
var params = [-imageNaturalWidth / 2, -imageNaturalHeight / 2, imageNaturalWidth, imageNaturalHeight];
canvas.width = normalizeDecimalNumber(width);
canvas.height = normalizeDecimalNumber(height);
context.fillStyle = fillColor;
context.fillRect(0, 0, width, height);
context.save();
context.translate(width / 2, height / 2);
context.rotate(rotate * Math.PI / 180);
context.scale(scaleX, scaleY);
context.imageSmoothingEnabled = !!imageSmoothingEnabled;
context.imageSmoothingQuality = imageSmoothingQuality;
context.drawImage.apply(context, [image].concat(toConsumableArray($.map(params, function (param) {
return Math.floor(normalizeDecimalNumber(param));
}))));
context.restore();
return canvas;
}
var fromCharCode = String.fromCharCode;
/**
* Get string from char code in data view.
* @param {DataView} dataView - The data view for read.
* @param {number} start - The start index.
* @param {number} length - The read length.
* @returns {string} The read result.
*/
function getStringFromCharCode(dataView, start, length) {
var str = '';
var i = void 0;
length += start;
for (i = start; i < length; i += 1) {
str += fromCharCode(dataView.getUint8(i));
}
return str;
}
var REGEXP_DATA_URL_HEAD = /^data:.*,/;
/**
* Transform Data URL to array buffer.
* @param {string} dataURL - The Data URL to transform.
* @returns {ArrayBuffer} The result array buffer.
*/
function dataURLToArrayBuffer(dataURL) {
var base64 = dataURL.replace(REGEXP_DATA_URL_HEAD, '');
var binary = atob(base64);
var arrayBuffer = new ArrayBuffer(binary.length);
var uint8 = new Uint8Array(arrayBuffer);
$.each(uint8, function (i) {
uint8[i] = binary.charCodeAt(i);
});
return arrayBuffer;
}
/**
* Transform array buffer to Data URL.
* @param {ArrayBuffer} arrayBuffer - The array buffer to transform.
* @param {string} mimeType - The mime type of the Data URL.
* @returns {string} The result Data URL.
*/
function arrayBufferToDataURL(arrayBuffer, mimeType) {
var uint8 = new Uint8Array(arrayBuffer);
var data = '';
// TypedArray.prototype.forEach is not supported in some browsers.
$.each(uint8, function (i, value) {
data += fromCharCode(value);
});
return 'data:' + mimeType + ';base64,' + btoa(data);
}
/**
* Get orientation value from given array buffer.
* @param {ArrayBuffer} arrayBuffer - The array buffer to read.
* @returns {number} The read orientation value.
*/
function getOrientation(arrayBuffer) {
var dataView = new DataView(arrayBuffer);
var orientation = void 0;
var littleEndian = void 0;
var app1Start = void 0;
var ifdStart = void 0;
// Only handle JPEG image (start by 0xFFD8)
if (dataView.getUint8(0) === 0xFF && dataView.getUint8(1) === 0xD8) {
var length = dataView.byteLength;
var offset = 2;
while (offset < length) {
if (dataView.getUint8(offset) === 0xFF && dataView.getUint8(offset + 1) === 0xE1) {
app1Start = offset;
break;
}
offset += 1;
}
}
if (app1Start) {
var exifIDCode = app1Start + 4;
var tiffOffset = app1Start + 10;
if (getStringFromCharCode(dataView, exifIDCode, 4) === 'Exif') {
var endianness = dataView.getUint16(tiffOffset);
littleEndian = endianness === 0x4949;
if (littleEndian || endianness === 0x4D4D /* bigEndian */) {
if (dataView.getUint16(tiffOffset + 2, littleEndian) === 0x002A) {
var firstIFDOffset = dataView.getUint32(tiffOffset + 4, littleEndian);
if (firstIFDOffset >= 0x00000008) {
ifdStart = tiffOffset + firstIFDOffset;
}
}
}
}
}
if (ifdStart) {
var _length = dataView.getUint16(ifdStart, littleEndian);
var _offset = void 0;
var i = void 0;
for (i = 0; i < _length; i += 1) {
_offset = ifdStart + i * 12 + 2;
if (dataView.getUint16(_offset, littleEndian) === 0x0112 /* Orientation */) {
// 8 is the offset of the current tag's value
_offset += 8;
// Get the original orientation value
orientation = dataView.getUint16(_offset, littleEndian);
// Override the orientation with its default value
dataView.setUint16(_offset, 1, littleEndian);
break;
}
}
}
return orientation;
}
/**
* Parse Exif Orientation value.
* @param {number} orientation - The orientation to parse.
* @returns {Object} The parsed result.
*/
function parseOrientation(orientation) {
var rotate = 0;
var scaleX = 1;
var scaleY = 1;
switch (orientation) {
// Flip horizontal
case 2:
scaleX = -1;
break;
// Rotate left 180°
case 3:
rotate = -180;
break;
// Flip vertical
case 4:
scaleY = -1;
break;
// Flip vertical and rotate right 90°
case 5:
rotate = 90;
scaleY = -1;
break;
// Rotate right 90°
case 6:
rotate = 90;
break;
// Flip horizontal and rotate right 90°
case 7:
rotate = 90;
scaleX = -1;
break;
// Rotate left 90°
case 8:
rotate = -90;
break;
default:
}
return {
rotate: rotate,
scaleX: scaleX,
scaleY: scaleY
};
}
var render = {
render: function render() {
this.initContainer();
this.initCanvas();
this.initCropBox();
this.renderCanvas();
if (this.cropped) {
this.renderCropBox();
}
},
initContainer: function initContainer() {
var $element = this.$element,
options = this.options,
$container = this.$container,
$cropper = this.$cropper;
$cropper.addClass(CLASS_HIDDEN);
$element.removeClass(CLASS_HIDDEN);
$cropper.css(this.container = {
width: Math.max($container.width(), Number(options.minContainerWidth) || 200),
height: Math.max($container.height(), Number(options.minContainerHeight) || 100)
});
$element.addClass(CLASS_HIDDEN);
$cropper.removeClass(CLASS_HIDDEN);
},
// Canvas (image wrapper)
initCanvas: function initCanvas() {
var container = this.container,
image = this.image;
var viewMode = this.options.viewMode;
var rotated = Math.abs(image.rotate) % 180 === 90;
var naturalWidth = rotated ? image.naturalHeight : image.naturalWidth;
var naturalHeight = rotated ? image.naturalWidth : image.naturalHeight;
var aspectRatio = naturalWidth / naturalHeight;
var canvasWidth = container.width;
var canvasHeight = container.height;
if (container.height * aspectRatio > container.width) {
if (viewMode === 3) {
canvasWidth = container.height * aspectRatio;
} else {
canvasHeight = container.width / aspectRatio;
}
} else if (viewMode === 3) {
canvasHeight = container.width / aspectRatio;
} else {
canvasWidth = container.height * aspectRatio;
}
var canvas = {
aspectRatio: aspectRatio,
naturalWidth: naturalWidth,
naturalHeight: naturalHeight,
width: canvasWidth,
height: canvasHeight
};
canvas.left = (container.width - canvasWidth) / 2;
canvas.top = (container.height - canvasHeight) / 2;
canvas.oldLeft = canvas.left;
canvas.oldTop = canvas.top;
this.canvas = canvas;
this.limited = viewMode === 1 || viewMode === 2;
this.limitCanvas(true, true);
this.initialImage = $.extend({}, image);
this.initialCanvas = $.extend({}, canvas);
},
limitCanvas: function limitCanvas(isSizeLimited, isPositionLimited) {
var options = this.options,
container = this.container,
canvas = this.canvas,
cropBox = this.cropBox;
var viewMode = options.viewMode;
var aspectRatio = canvas.aspectRatio;
var cropped = this.cropped && cropBox;
if (isSizeLimited) {
var minCanvasWidth = Number(options.minCanvasWidth) || 0;
var minCanvasHeight = Number(options.minCanvasHeight) || 0;
if (viewMode > 0) {
if (viewMode > 1) {
minCanvasWidth = Math.max(minCanvasWidth, container.width);
minCanvasHeight = Math.max(minCanvasHeight, container.height);
if (viewMode === 3) {
if (minCanvasHeight * aspectRatio > minCanvasWidth) {
minCanvasWidth = minCanvasHeight * aspectRatio;
} else {
minCanvasHeight = minCanvasWidth / aspectRatio;
}
}
} else if (minCanvasWidth) {
minCanvasWidth = Math.max(minCanvasWidth, cropped ? cropBox.width : 0);
} else if (minCanvasHeight) {
minCanvasHeight = Math.max(minCanvasHeight, cropped ? cropBox.height : 0);
} else if (cropped) {
minCanvasWidth = cropBox.width;
minCanvasHeight = cropBox.height;
if (minCanvasHeight * aspectRatio > minCanvasWidth) {
minCanvasWidth = minCanvasHeight * aspectRatio;
} else {
minCanvasHeight = minCanvasWidth / aspectRatio;
}
}
}
var _getContainSizes = getContainSizes({
aspectRatio: aspectRatio,
width: minCanvasWidth,
height: minCanvasHeight
});
minCanvasWidth = _getContainSizes.width;
minCanvasHeight = _getContainSizes.height;
canvas.minWidth = minCanvasWidth;
canvas.minHeight = minCanvasHeight;
canvas.maxWidth = Infinity;
canvas.maxHeight = Infinity;
}
if (isPositionLimited) {
if (viewMode > 0) {
var newCanvasLeft = container.width - canvas.width;
var newCanvasTop = container.height - canvas.height;
canvas.minLeft = Math.min(0, newCanvasLeft);
canvas.minTop = Math.min(0, newCanvasTop);
canvas.maxLeft = Math.max(0, newCanvasLeft);
canvas.maxTop = Math.max(0, newCanvasTop);
if (cropped && this.limited) {
canvas.minLeft = Math.min(cropBox.left, cropBox.left + cropBox.width - canvas.width);
canvas.minTop = Math.min(cropBox.top, cropBox.top + cropBox.height - canvas.height);
canvas.maxLeft = cropBox.left;
canvas.maxTop = cropBox.top;
if (viewMode === 2) {
if (canvas.width >= container.width) {
canvas.minLeft = Math.min(0, newCanvasLeft);
canvas.maxLeft = Math.max(0, newCanvasLeft);
}
if (canvas.height >= container.height) {
canvas.minTop = Math.min(0, newCanvasTop);
canvas.maxTop = Math.max(0, newCanvasTop);
}
}
}
} else {
canvas.minLeft = -canvas.width;