-
Notifications
You must be signed in to change notification settings - Fork 80
/
index.js
2190 lines (2030 loc) · 70.1 KB
/
index.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
/* global define */
/// <reference path="./index.d.ts" />
(function (factory) {
if (typeof define === "function" && define.amd) {
// AMD. Register as an anonymous module.
define(["prefix-umd", "exif-js", "transformation-matrix"], factory);
} else if (typeof module === "object" && module.exports) {
// Node/CommonJS
module.exports = factory(
require("prefix-umd"),
require("exif-js"),
require("transformation-matrix")
);
} else {
// Browser globals
window.SimpleCrop = factory(
window.Prefix,
window.EXIF,
window.TransformationMatrix
);
}
})(function (Prefix, EXIF, TransformationMatrix) {
//兼容性处理
function whichTransitionEvent() {
var t;
var el = document.createElement("div");
var transitions = {
transition: "transitionend",
OTransition: "oTransitionEnd",
MozTransition: "transitionend",
WebkitTransition: "webkitTransitionEnd",
MsTransition: "msTransitionEnd",
};
for (t in transitions) {
if (el.style[t] !== undefined) {
return transitions[t];
}
}
}
var transitionEndEvent = whichTransitionEvent();
var transformProperty = Prefix.prefix("transform");
var transitionProperty = Prefix.prefix("transition");
//includes方法兼容
if (!Array.prototype.includes) {
Object.defineProperty(Array.prototype, "includes", {
value: function (valueToFind, fromIndex) {
var o = Object(this);
var len = o.length >>> 0;
if (len === 0) {
return false;
}
var n = fromIndex | 0;
var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
function sameValueZero(x, y) {
return (
x === y ||
(typeof x === "number" &&
typeof y === "number" &&
isNaN(x) &&
isNaN(y))
);
}
while (k < len) {
if (sameValueZero(o[k], valueToFind)) {
return true;
}
k++;
}
return false;
},
});
}
/**
* ------------------------------------
* 配置
* @param title 标题
* @param visible 组件是否可见
* @param debug 是否开启调试模式(pc、mobile)
* @param $container 容器(pc、mobile)
* ------------------------------------
* 裁剪图片
* @param src 图片地址
* @param size 裁剪图片目标尺寸
* initSize 裁剪图片初始尺寸
* originImage 初始图片
* _orientation 图片方向
* ------------------------------------
* 裁剪框样式
* @param positionOffset 裁剪框屏幕偏移
* @param boldCornerLen 裁剪框边角加粗长度
* @param boldCornerWidth 裁剪框边角加粗宽度
* @param coverColor 遮罩背景颜色
* @param cropSizePercent 裁剪框占裁剪显示区域的比例
* @param borderWidth 裁剪框边框宽度
* @param borderColor 裁剪框边框颜色
* @param coverDraw 裁剪框辅助线绘制函数
* @param borderDraw 裁剪框边框绘制函数
* ------------------------------------
* 裁剪框拖拽
* @param cursorHoverWidth 裁剪框拖动触发范围
* @param isFixedAspectRatio 是否固定宽高比
* ------------------------------------
* 功能按钮
* @param funcBtns 功能按钮配置数组
* @param cropCallback 图片裁剪完成回调函数
* @param uploadCallback 重新上传裁剪图片回调函数
* @param closeCallback 关闭裁剪组件回调函数
* ------------------------------------
* 旋转刻度盘
* @param rotateSlider 是否开启旋转刻度盘
* @param startAngle 旋转刻度盘开始角度
* @param endAngle 旋转刻度盘结束角度
* @param gapAngle 旋转刻度盘间隔角度
* @param lineationItemWidth 旋转刻度盘间隔宽度
* lineationWidth 根据上述参数计算出的旋转刻度盘总宽度
* rotateWidth 旋转刻度盘显示宽度
* ------------------------------------
* 尺寸(为了减少计算的复杂性,所有坐标都统一为屏幕坐标及尺寸)
* maskViewSize 容器屏幕尺寸
* initCropRect 初始裁剪框屏幕尺寸
* cropRect 裁剪框屏幕尺寸
* cropPoints 裁剪框顶点坐标
* cropCenter 裁剪框中心点坐标
* contentWidth 图片显示宽度
* contentHeight 图片显示高度
* contentPoints 图片顶点坐标
* initContentPoints 图片初始顶点坐标
* _contentCurMoveX 图片 X 轴方向上的总位移
* _contentCurMoveY 图片 Y 轴方向上的总位移
* ------------------------------------
* 鼠标滚轮缩放
* _wheelTimeout 定时器
* ------------------------------------
* 拖动裁剪框
* _moveCursor 拖拽状态
* _moveCursorAction 裁剪框拖动进行时
*
* move 图片拖拽
* crop_leftTop 裁剪框左上拖拽
* crop_leftBottom 裁剪框左下拖拽
* crop_rightTop 裁剪框右上拖拽
* crop_rightBottom 裁剪框右下拖拽
* crop_left 裁剪框左拖拽
* crop_right 裁剪框右拖拽
* crop_top 裁剪框上拖拽
* crop_bottom 裁剪框下拖拽
* ------------------------------------
* 双指缩放
* _multiPoint 是否开始多点触控
* fingerLen 双指距离
* fingerScale 双指缩放倍数
* fingerCenter 双指操作中心
* ------------------------------------
* 其它
* times 实际尺寸/显示尺寸
* initScale 初始缩放倍数
* $resultCanvas 裁切结果(pc、mobile)
* resultSrc 裁剪结果(wechat)
* isSupportTouch 是否支持 touch 事件(pc、mobile)
* passiveSupported 事件是否支持 passive(pc、mobile)
* _precision 计算精度
*/
function SimpleCrop(params) {
//配置
this.id = "crop-" + new Date().getTime();
this.initSize = {
width: params.size.width,
height: params.size.height,
}; // 初始尺寸
this.visible = params.visible != null ? params.visible : true; //默认显示
this.debug = params.debug != null ? params.debug : false;
this.$container =
params.$container != null ? params.$container : document.body; //容器
//其它
var self = this;
self.passiveSupported = false; //判断是否支持 passive
try {
var options = Object.defineProperty({}, "passive", {
get: function () {
self.passiveSupported = true;
},
});
window.addEventListener("test", null, options);
} catch (err) {
//nothing
}
this.isSupportTouch = "ontouchend" in document ? true : false; //判断是否支持 touch 事件
this._precision = 5; // 计算精度
//操作状态
this._multiPoint = false; //是否开始多点触控
this._rotateScale = 1; //旋转缩放倍数
this._baseMoveX = 0; //旋转刻度盘位置初始化偏移量
this._curMoveX = 0; //旋转刻度盘位置当前总偏移量
this._changedX = 0; //旋转刻度盘当前偏移量
this._downPoints = []; //操作点坐标数组
this._isControl = false; //是否正在操作
/**
* 旋转交互分为两种:
* 一种是整角旋转(90度);
* 另一种是基于整角旋转的基础上正负45度旋转。
*/
this._baseAngle = 0;
this.scaleTimes = 1; //缩放倍数
this.rotateAngle = 0; //旋转角度
this.construct();
//注意 construct 和 bindEvent 中间函数的先后顺序
this.initFuncBtns(params); //初始化功能按钮
this.initRotateSlider(params); //初始化旋转刻度盘
this.initChilds();
this.initTitle(params);
this.initBox(params);
this.initBoxBorder(params, true);
this.initBoxCursor(params);
this.setImage(params.src != null ? params.src : this.src);
this.bindEvent();
}
//初始化标题
SimpleCrop.prototype.initTitle = function (params) {
this.title = params.title != null ? params.title : "";
this.$title = document.querySelector("#" + this.id + " .crop-title");
this.$title.innerText = this.title;
};
//初始化裁剪框边框以及辅助线
SimpleCrop.prototype.initBoxBorder = function (params, onlyInit) {
this.borderWidth = params.borderWidth != null ? params.borderWidth : 2;
this.borderColor = params.borderColor != null ? params.borderColor : "#fff";
this.boldCornerLen =
params.boldCornerLen != null ? params.boldCornerLen : 32;
this.boldCornerWidth = params.boldCornerWidth ? params.boldCornerWidth : 4;
this.coverColor =
params.coverColor != null ? params.coverColor : "rgba(0,0,0,.3)";
this.coverDraw =
params.coverDraw != null ? params.coverDraw : function () { };
this.borderDraw =
params.borderDraw != null ? params.borderDraw : this.defaultBorderDraw;
if (!onlyInit) {
this.borderDraw(this.$cropCover);
this.coverDraw(this.$cropCover);
}
};
// 初始化裁剪框拖拽相关参数
SimpleCrop.prototype.initBoxCursor = function (params) {
const defaultCursorWidth = this.isSupportTouch
? this.borderWidth * 10
: this.borderWidth * 2;
this.cursorHoverWidth =
params.cursorHoverWidth != null
? params.cursorHoverWidth
: defaultCursorWidth;
this.isFixedAspectRatio =
params.isFixedAspectRatio != null ? params.isFixedAspectRatio : false;
};
//初始化功能按钮
SimpleCrop.prototype.initFuncBtns = function (params) {
/**
* 默认功能按钮为取消、裁剪、90度旋转、重置
* upload 重新上传
* crop 裁剪
* close 取消
* around 90度旋转
* reset 重置
*/
this.funcBtns =
params.funcBtns != null
? params.funcBtns
: ["close", "crop", "around", "reset"];
this.cropCallback =
params.cropCallback != null ? params.cropCallback : function () { };
this.closeCallback =
params.closeCallback != null ? params.closeCallback : function () { };
this.uploadCallback =
params.uploadCallback != null ? params.uploadCallback : function () { };
this.$cropBtns = document.querySelector("#" + this.id + " .crop-btns");
var html = "";
if (this.funcBtns.includes("upload")) {
html += '<div class="upload-btn-container">';
html += '<button class="upload-btn"></button>';
html += '<input type="file" accept="image/png,image/jpeg">';
html += "</div>";
}
if (this.funcBtns.includes("close")) {
html += '<button class="crop-close"></button>';
}
if (this.funcBtns.includes("around")) {
html += '<button class="crop-around"></button>';
}
if (this.funcBtns.includes("reset")) {
html += '<button class="crop-reset"></button>';
}
if (this.funcBtns.includes("crop")) {
html += '<button class="crop-btn"></button>';
}
this.$cropBtns.innerHTML = html;
//重新上传
if (this.funcBtns.includes("upload")) {
if (this.$uploadBtn) {
this.$uploadBtn.removeEventListener("change", this.__uploadInput);
} else {
this.__uploadInput = this.uploadInput.bind(this);
}
this.$uploadBtn = document.querySelector(
"#" + this.id + " .upload-btn-container"
);
this.$uploadInput = document.querySelector(
"#" + this.id + " .upload-btn-container input"
);
this.$uploadBtn.addEventListener("change", this.__uploadInput);
}
//裁剪
if (this.funcBtns.includes("crop")) {
if (this.$cropBtn) {
this.$cropBtn.removeEventListener("click", this.__crop);
} else {
this.__crop = this.crop.bind(this);
}
this.$cropBtn = document.querySelector("#" + this.id + " .crop-btn");
this.$cropBtn.addEventListener("click", this.__crop);
}
//整角旋转
if (this.funcBtns.includes("around")) {
if (this.$aroundBtn) {
this.$aroundBtn.removeEventListener("click", this.__around);
} else {
this.__around = this.around.bind(this);
}
this.$aroundBtn = document.querySelector("#" + this.id + " .crop-around");
this.$aroundBtn.addEventListener("click", this.__around);
}
//还原
if (this.funcBtns.includes("reset")) {
if (this.$resetBtn) {
this.$resetBtn.removeEventListener("click", this.reset);
} else {
this.__reset = this.reset.bind(this);
}
this.$resetBtn = document.querySelector("#" + this.id + " .crop-reset");
this.$resetBtn.addEventListener("click", this.__reset);
}
//关闭
if (this.funcBtns.includes("close")) {
if (this.$closeBtn) {
this.$closeBtn.removeEventListener("click", this.close);
} else {
this.__close = this.close.bind(this);
}
this.$closeBtn = document.querySelector("#" + this.id + " .crop-close");
this.$closeBtn.addEventListener("click", this.__close);
}
if (this.funcBtns.length > 0) {
this.$cropBtns.style.visibility = "";
} else {
this.$cropBtns.style.visibility = "hidden";
}
};
//初始化旋转刻度盘
SimpleCrop.prototype.initRotateSlider = function (params) {
this.rotateSlider =
params.rotateSlider != null ? params.rotateSlider : true; //默认开启
this.startAngle = params.startAngle != null ? params.startAngle : -90;
this.endAngle = params.endAngle != null ? params.endAngle : 90;
this.gapAngle = params.gapAngle != null ? params.gapAngle : 10;
this.lineationItemWidth =
params.lineationItemWidth != null ? params.lineationItemWidth : 40.5;
this.lineationItemWidth =
this.lineationItemWidth >= 40.5 ? this.lineationItemWidth : 40.5; // 最小宽度限制
//开始角度需要小于0,结束角度需要大于0,且开始角度和结束角度之间存在大于0的整数个间隔
this.startAngle = this.startAngle < 0 ? parseInt(this.startAngle) : 0;
this.endAngle = this.endAngle > 0 ? parseInt(this.endAngle) : 0;
this.gapAngle = this.gapAngle > 0 ? parseInt(this.gapAngle) : 3;
if ((this.endAngle - this.startAngle) % this.gapAngle != 0) {
this.endAngle =
Math.ceil((this.endAngle - this.startAngle) / this.gapAngle) *
this.gapAngle +
this.startAngle;
}
this.lineationWidth =
this.lineationItemWidth *
((this.endAngle - this.startAngle) / this.gapAngle + 1);
this.$cropRotate = document.querySelector("#" + this.id + " .crop-rotate");
this.$lineation = document.querySelector("#" + this.id + " .lineation");
this.$rotateCurrent = document.querySelector("#" + this.id + " .current");
var rotateStyle = window.getComputedStyle(this.$cropRotate);
this.rotateWidth = parseFloat(rotateStyle.getPropertyValue("width")); // 旋转刻度盘显示宽度
this._baseMoveX = -(
(this.lineationWidth * (0 - this.startAngle + this.gapAngle / 2)) /
(this.endAngle - this.startAngle + this.gapAngle) -
this.rotateWidth / 2
); //开始角度大于 0 且结束角度小于 0,以 0 度为起点
var angle = this.rotateAngle - this._baseAngle;
this._curMoveX =
(angle * this.lineationWidth) /
(this.endAngle - this.startAngle + this.gapAngle) +
this._baseMoveX;
//超出滚动边界,旋转刻度盘重置
if (
this._curMoveX > 0 ||
this._curMoveX < this.rotateWidth - this.lineationWidth
) {
this.startControl();
this._curMoveX = this._baseMoveX;
this._baseAngle = 0;
this.rotateAngle = 0;
this._changedX = 0;
this._rotateScale = 1;
this.transform(true);
this.endControl();
}
//setData
var html = "";
for (var i = this.startAngle; i <= this.endAngle; i += this.gapAngle) {
html +=
'<li><div class="number">' + i + '</div><div class="bg"></div></li>';
}
this.$lineation.innerHTML = html;
this.$lineation.style.width = this.lineationWidth + "px";
this.$lineation.style[transformProperty] =
"translateX(" + this._curMoveX + "px)";
if (this.rotateSlider) {
this.$cropRotate.style.visibility = "";
} else {
this.$cropRotate.style.visibility = "hidden";
}
};
//初始化相关子元素
SimpleCrop.prototype.initChilds = function () {
this.$cropMask = document.querySelector("#" + this.id + " .crop-mask");
var maskRect = this.$cropMask.getBoundingClientRect();
this.maskViewSize = {
top: maskRect.top,
left: maskRect.left,
width: maskRect.width,
height: maskRect.height,
};
this.$cropCover = document.querySelector("#" + this.id + " .crop-cover");
this.cropCoverContext = this.$cropCover.getContext("2d");
this.$cropCover.width = this.maskViewSize.width * window.devicePixelRatio;
this.$cropCover.height = this.maskViewSize.height * window.devicePixelRatio;
};
// 初始化裁剪图片目标尺寸、裁剪框显示比例、偏移等参数
SimpleCrop.prototype.initBox = function (params) {
this.size = params.size;
this.positionOffset =
params.positionOffset != null
? params.positionOffset
: {
top: 0,
left: 0,
};
this.cropSizePercent =
params.cropSizePercent != null ? params.cropSizePercent : 0.5; //默认0.5则表示高度或者宽度最多占50%
};
// 根据裁剪图片目标尺寸、裁剪框显示比例、偏移等参数重现绘制裁剪框
SimpleCrop.prototype.updateBox = function (params) {
this.initBox(params);
this.times =
this.size.width / this.maskViewSize.width >
this.size.height / this.maskViewSize.height
? this.size.width / this.maskViewSize.width / this.cropSizePercent
: this.size.height / this.maskViewSize.height / this.cropSizePercent;
//裁剪框位置相关
this.cropRect = {
width: this.size.width / this.times,
height: this.size.height / this.times,
};
this.cropRect.left =
(this.maskViewSize.width - this.cropRect.width) / 2 -
this.positionOffset.left;
this.cropRect.top =
(this.maskViewSize.height - this.cropRect.height) / 2 -
this.positionOffset.top;
this.initCropRect = {
left: this.cropRect.left,
top: this.cropRect.top,
width: this.cropRect.width,
height: this.cropRect.height,
};
this.cropPoints = this.rectToPoints(this.cropRect);
this.cropCenter = this.getPointsCenter(this.cropPoints);
this.borderDraw(this.$cropCover);
this.coverDraw(this.$cropCover);
this.transform(false, true);
};
//获取操作点
SimpleCrop.prototype.getControlPoints = function (e) {
if (e.touches) {
return e.touches;
} else {
return [
{
clientX: e.clientX,
clientY: e.clientY,
},
];
}
};
//获取操作事件名称
SimpleCrop.prototype.getControlEvents = function () {
if (this.isSupportTouch) {
return {
start: "touchstart",
move: "touchmove",
end: "touchend",
cancel: "touchcancel",
};
} else {
return {
start: "mousedown",
move: "mousemove",
end: "mouseup",
cancel: "mouseleave",
};
}
};
//html结构
SimpleCrop.prototype.construct = function () {
var html = "";
html += '<div class="crop-component">';
html += '<p class="crop-title"></p>'; // 标题
html += '<div class="crop-mask">';
html += '<canvas class="crop-cover"></canvas>';
html += "</div>";
//旋转刻度盘
if (this.rotateSlider) {
html += '<div class="crop-rotate">';
} else {
html += '<div class="crop-rotate" style="visibility:hidden;">';
}
html += '<ul class="lineation">';
html += "</ul>";
html += '<div class="current"></div>';
html += "</div>";
//功能按钮
html += '<div class="crop-btns" style="visibility:hidden;"></div>';
html += "</div>";
this.$target = document.createElement("div");
this.$target.id = this.id;
this.$target.classList.add("crop-whole-cover");
if (this.visible) {
this.$target.style.visibility = "";
} else {
this.$target.style.visibility = "hidden";
}
this.$target.innerHTML = html;
this.$container.appendChild(this.$target);
};
//默认绘制裁剪框
SimpleCrop.prototype.defaultBorderDraw = function ($cropCover) {
var borderWidth = this.borderWidth;
var boldCornerWidth = this.boldCornerWidth;
var boldCornerLen = this.boldCornerLen;
boldCornerLen =
boldCornerLen >= borderWidth * 2 ? boldCornerLen : borderWidth * 2; // 边角加粗长度至少是边框的两倍
var coverWidth = $cropCover.width;
var coverHeight = $cropCover.height;
this.cropCoverContext.clearRect(0, 0, coverWidth, coverHeight);
this.cropCoverContext.fillStyle = this.coverColor;
this.cropCoverContext.fillRect(0, 0, coverWidth, coverHeight);
//绘制边框(边框内嵌)
var borderRect = {
left: this.cropRect.left * window.devicePixelRatio,
top: this.cropRect.top * window.devicePixelRatio,
width: this.cropRect.width * window.devicePixelRatio,
height: this.cropRect.height * window.devicePixelRatio,
};
this.cropCoverContext.fillStyle = this.borderColor;
this.cropCoverContext.fillRect(
borderRect.left,
borderRect.top,
borderRect.width,
borderRect.height
);
if (this.boldCornerLen > 0) {
//边框四个角加粗
this.cropCoverContext.fillRect(
borderRect.left - boldCornerWidth,
borderRect.top - boldCornerWidth,
boldCornerLen,
boldCornerLen
); //左上角
this.cropCoverContext.fillRect(
borderRect.left + borderRect.width - boldCornerLen + boldCornerWidth,
borderRect.top - boldCornerWidth,
boldCornerLen,
boldCornerLen
); //右上角
this.cropCoverContext.fillRect(
borderRect.left - boldCornerWidth,
borderRect.top + borderRect.height - boldCornerLen + boldCornerWidth,
boldCornerLen,
boldCornerLen
); //左下角
this.cropCoverContext.fillRect(
borderRect.left + borderRect.width - boldCornerLen + boldCornerWidth,
borderRect.top + borderRect.height - boldCornerLen + boldCornerWidth,
boldCornerLen,
boldCornerLen
); //右下角
}
// 文字
var txtCanvas = document.createElement("canvas");
txtCanvas.width = borderRect.width;
txtCanvas.height = 24;
var ctx = txtCanvas.getContext("2d");
ctx.font = "24px Calibri";
ctx.fillStyle = this.borderColor;
ctx.textBaseline = "middle";
ctx.textAlign = "center";
var curSizeWidth = parseInt(
(this.size.width * this.cropRect.width) / this.initCropRect.width
);
var curSizeHeight = parseInt(
(this.size.height * this.cropRect.height) / this.initCropRect.height
);
ctx.fillText(
curSizeWidth + " x " + curSizeHeight,
txtCanvas.width / 2,
txtCanvas.height / 2
);
this.cropCoverContext.drawImage(
txtCanvas,
0,
0,
txtCanvas.width,
txtCanvas.height,
borderRect.left,
borderRect.top - 24 - 2 * this.boldCornerWidth,
txtCanvas.width,
txtCanvas.height
);
//清空内容区域
this.cropCoverContext.clearRect(
borderRect.left + borderWidth,
borderRect.top + borderWidth,
borderRect.width - 2 * borderWidth,
borderRect.height - 2 * borderWidth
);
};
//初始化
SimpleCrop.prototype.init = function () {
var width = this.contentWidth / 2;
var height = this.contentHeight / 2;
this.initContentPoints = [
{
x: -width,
y: height,
},
{
x: width,
y: height,
},
{
x: width,
y: -height,
},
{
x: -width,
y: -height,
},
];
this.contentPoints = this.initContentPoints.slice();
//计算初始缩放倍数
if (
this.size.width / this.size.height >
this.contentWidth / this.contentHeight
) {
this.initScale = this.size.width / this.contentWidth;
} else {
this.initScale = this.size.height / this.contentHeight;
}
this.reset();
};
//重置
SimpleCrop.prototype.reset = function () {
this.startControl();
this._contentCurMoveX = -this.positionOffset.left;
this._contentCurMoveY = -this.positionOffset.top;
this._rotateScale = 1;
this._baseAngle = 0;
this.rotateAngle = 0;
this._curMoveX = this._baseMoveX;
this._changedX = 0;
this.$lineation.style[transformProperty] =
"translateX(" + this._baseMoveX + "px)";
this.scaleTimes = this.initScale;
this.updateBox({
positionOffset: this.positionOffset,
cropSizePercent: this.cropSizePercent,
size: {
width: this.initSize.width,
height: this.initSize.height,
},
});
this.endControl();
};
//加载图片
SimpleCrop.prototype.load = function () {
var self = this;
self.originImage.onload = function () {
EXIF.getData(self.originImage, function () {
self._orientation = EXIF.getTag(this, "Orientation");
self.getRealCotentSize();
self.transformCoordinates();
self.init();
});
};
};
//设置裁剪图片
SimpleCrop.prototype.setImage = function (image) {
// base64转Blob
function dataURItoBlob(dataURI) {
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]; // mime类型
var byteString = atob(dataURI.split(',')[1]); //base64 解码
var arrayBuffer = new ArrayBuffer(byteString.length); //创建缓冲数组
var intArray = new Uint8Array(arrayBuffer); //创建视图
for (var i = 0; i < byteString.length; i++) {
intArray[i] = byteString.charCodeAt(i);
}
return new Blob([intArray], { type: mimeString });
}
// 解决兼容性问题。
function getObjectURL(blob) {
var url = null;
if (window.createObjectURL != undefined) {
url = window.createObjectURL(blob);
} else if (window.URL != undefined) {
url = window.URL.createObjectURL(blob);
} else if (window.webkitURL != undefined) {
url = window.webkitURL.createObjectURL(blob);
}
return url;
}
if (image != null && image != "") {
var self = this;
var type = Object.prototype.toString.call(image);
if (type === "[object String]") {
//字符串
self.src = image;
self.originImage = new Image();
self.originImage.crossOrigin = "Anonymous";
self.load();
const imgBlob = dataURItoBlob(image)
self.originImage.src = getObjectURL(imgBlob);
self.uploadCallback(self.src);
} else if (type === "[object File]") {
//文件
self.fileToSrc(image, function (src) {
self.src = src;
self.originImage = new Image();
self.originImage.crossOrigin = "Anonymous";
self.originImage.src = self.src;
self.load();
self.uploadCallback(self.src);
});
}
}
};
//显示
SimpleCrop.prototype.show = function (image) {
if (image) {
this.setImage(image);
}
this.visible = true;
this.$target.style.visibility = "";
};
//隐藏
SimpleCrop.prototype.hide = function () {
this.visible = false;
this.$target.style.visibility = "hidden";
};
//关闭
SimpleCrop.prototype.close = function () {
this.hide();
this.closeCallback();
};
//裁剪
SimpleCrop.prototype.crop = function () {
this.getCropImage();
this.cropCallback(this.$resultCanvas);
this.hide();
};
//上传
SimpleCrop.prototype.uploadInput = function (evt) {
var files = evt.target.files;
if (files.length > 0) {
this.show(files[0]);
}
this.$uploadInput.value = ""; //清空value属性,从而保证用户修改文件内容但是没有修改文件名时依然能上传成功
};
//整角旋转
SimpleCrop.prototype.around = function () {
this.startControl();
this.rotateAngle = (this._baseAngle - 90) % 360;
this._baseAngle = this.rotateAngle;
this._curMoveX = this._baseMoveX;
this._changedX = 0;
this._rotateScale = 1;
this.$lineation.style[transformProperty] =
"translateX(" + this._baseMoveX + "px)";
this.transform(false, true);
this.endControl();
};
// 裁剪框拖拽鼠标样式
SimpleCrop.prototype.moveCursor = function (touches) {
var point = {
x: touches[0].clientX - this.maskViewSize.left,
y: touches[0].clientY - this.maskViewSize.top,
};
var innerRect = {
left: this.cropRect.left + this.cursorHoverWidth,
top: this.cropRect.top + this.cursorHoverWidth,
width: this.cropRect.width - 2 * this.cursorHoverWidth,
height: this.cropRect.height - 2 * this.cursorHoverWidth,
};
var outerRect = {
left: this.cropRect.left - this.cursorHoverWidth,
top: this.cropRect.top - this.cursorHoverWidth,
width: this.cropRect.width + 2 * this.cursorHoverWidth,
height: this.cropRect.height + 2 * this.cursorHoverWidth,
};
if (
point.x >= outerRect.left &&
point.x <= outerRect.left + outerRect.width &&
point.y >= outerRect.top &&
point.y <= outerRect.height + outerRect.top &&
!(
point.x >= innerRect.left &&
point.x <= innerRect.left + innerRect.width &&
point.y >= innerRect.top &&
point.y <= innerRect.height + innerRect.top
)
) {
if (
point.x <= outerRect.left + this.boldCornerLen &&
point.y <= outerRect.top + this.boldCornerLen
) {
this.$cropCover.style.cursor = "nwse-resize"; // 左上角
this._moveCursor = "crop_leftTop";
} else if (
point.x <= outerRect.left + this.boldCornerLen &&
point.y >= outerRect.height + outerRect.top - this.boldCornerLen
) {
this.$cropCover.style.cursor = "nesw-resize"; // 左下角
this._moveCursor = "crop_leftBottom";
} else if (
point.x >= outerRect.width + outerRect.left - this.boldCornerLen &&
point.y <= outerRect.top + this.boldCornerLen
) {
this.$cropCover.style.cursor = "nesw-resize"; // 右上角
this._moveCursor = "crop_rightTop";
} else if (
point.x >= outerRect.width + outerRect.left - this.boldCornerLen &&
point.y >= outerRect.height + outerRect.top - this.boldCornerLen
) {
this.$cropCover.style.cursor = "nwse-resize"; // 右下角
this._moveCursor = "crop_rightBottom";
} else if (
point.y <= outerRect.top + this.boldCornerLen &&
!this.isFixedAspectRatio
) {
this.$cropCover.style.cursor = "ns-resize"; // 水平上
this._moveCursor = "crop_top";
} else if (
point.y >= outerRect.height + outerRect.top - this.boldCornerLen &&
!this.isFixedAspectRatio
) {
this.$cropCover.style.cursor = "ns-resize"; // 水平下
this._moveCursor = "crop_bottom";
} else if (
point.x <= outerRect.left + this.boldCornerLen &&
!this.isFixedAspectRatio
) {
this.$cropCover.style.cursor = "ew-resize"; // 竖直左
this._moveCursor = "crop_left";
} else if (
point.x >= outerRect.width + outerRect.left - this.boldCornerLen &&
!this.isFixedAspectRatio
) {
this.$cropCover.style.cursor = "ew-resize"; // 竖直右
this._moveCursor = "crop_right";
}
} else {
this.$cropCover.style.cursor = "move";
this._moveCursor = "move";
}
};
//裁剪框移动
SimpleCrop.prototype.cropMove = function (touches) {
var movePos = touches[0];
var startPos = this._downPoints[0];
var moveCursorAction = this._moveCursorAction.toLowerCase();
var changeX = movePos.clientX - startPos.clientX;
var finalMovePos = {
clientX: movePos.clientX,
clientY: movePos.clientY,
};
if (
(moveCursorAction.indexOf("left") != -1 ||
moveCursorAction.indexOf("right") != -1) &&
(moveCursorAction.indexOf("top") != -1 ||
moveCursorAction.indexOf("bottom") != -1)
) {
var tag = 0;
if (["crop_lefttop", "crop_rightbottom"].includes(moveCursorAction)) {
tag = 1;
} else {
tag = -1;
}
var fixedChangeY =
(changeX * this.initCropRect.height) / this.initCropRect.width;
finalMovePos.clientY = startPos.clientY + fixedChangeY * tag; // 以宽度变化为基准
}
if (moveCursorAction.indexOf("left") != -1) {
this.cropRect.left =
this.initCropRect.left + (finalMovePos.clientX - startPos.clientX);
this.cropRect.width =
this.initCropRect.width - (finalMovePos.clientX - startPos.clientX);
}
if (moveCursorAction.indexOf("right") != -1) {
this.cropRect.width =
this.initCropRect.width + (finalMovePos.clientX - startPos.clientX);
}
if (moveCursorAction.indexOf("top") != -1) {
this.cropRect.top =
this.initCropRect.top + (finalMovePos.clientY - startPos.clientY);
this.cropRect.height =
this.initCropRect.height - (finalMovePos.clientY - startPos.clientY);
}
if (moveCursorAction.indexOf("bottom") != -1) {
this.cropRect.height =
this.initCropRect.height + (finalMovePos.clientY - startPos.clientY);
}
if (this.cropRect.width <= this.boldCornerLen) {
this.cropRect.width = this.boldCornerLen;
}
if (this.cropRect.height <= this.boldCornerLen) {
this.cropRect.height = this.boldCornerLen;
}