-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathwepy-cropper.wpy
995 lines (836 loc) · 29.1 KB
/
wepy-cropper.wpy
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
<template>
<scroll-view class="cropper_main_container {{params.visable?'':'hidden'}}">
<view class="cropper_container">
<canvas class="original_canvas" canvas-id="originalCanvas" style="width:{{cropperChangableData.originalSize.width}}px;height:{{cropperChangableData.originalSize.height}}px;"></canvas>
<view class='cropper_canvas_container'>
<canvas class="canvas" canvas-id="canvas" style="left:{{cropperData.left}}px;top:{{cropperData.top}}px;width:{{cropperChangableData.scaleSize.width}}px;height:{{cropperChangableData.scaleSize.height}}px;"></canvas>
<canvas class="move_canvas" canvas-id="moveCanvas" style="left:{{cropperData.left}}px;top:{{cropperData.top}}px;width:{{cropperChangableData.scaleSize.width}}px;height:{{cropperChangableData.scaleSize.height}}px;"></canvas>
<movable-area class="cropper_movable_area_container" style="left:{{cropperData.left}}px;top:{{cropperData.top}}px;width:{{cropperChangableData.scaleSize.width}}px;height:{{cropperChangableData.scaleSize.height}}px;">
<block wx:if="{{cropperMovableItems}}">
<block wx:for="{{cropperMovableItems}}" wx:key="moveItem">
<movable-view class="move_item" style="width:{{cropperData.itemLength}}px; height:{{cropperData.itemLength}}px;" direction="all" x="{{item.x-cropperData.itemLength/2}}" y="{{item.y-cropperData.itemLength/2}}" bindtouchmove="moveEvent({{index}})" bindtouchend="endEvent({{index}})"></movable-view>
</block>
</block>
</movable-area>
</view>
</view>
<view class="cropper_toolbar">
<view class="button_item cancel_button" bindtap="hideCropper">
取消
</view>
<view class="button_item rotate_button" bindtap="rotateImage">
旋转
</view>
<block wx:if="{{cropperData.sizeType.length==2}}">
<view class="original_button button_item {{cropperData.original?'checked':''}}" bindtap="originalChange">
<!-- <view class='check_container'>
<view class='check_border'></view>
<view class='check_center'></view>
</view> -->
<view>原图</view>
</view>
</block>
<view class="crop_image_button button_item {{cropperChangableData.canCrop?'':'disable'}}" bindtap="{{cropperChangableData.canCrop?'cropImage':''}}">
完成
</view>
<!-- <view class="crop_image_button button_item" bindtap="cropImage">
完成
</view> -->
</view>
</scroll-view>
</template>
<script>
import wepy from 'wepy'
const device = wx.getSystemInfoSync();
const W = device.windowWidth;
const H = device.windowHeight - 50;
// 获取选中区域的(x, y, w, h)
const getCropRect = (cropperMovableItems) => {
let maxX = 0, maxY = 0
for (let key in cropperMovableItems) {
let item = cropperMovableItems[key]
maxX = item.x > maxX ? item.x : maxX
maxY = item.y > maxY ? item.y : maxY
}
let minX = maxX, minY = maxY
for (let key in cropperMovableItems) {
let item = cropperMovableItems[key]
minX = item.x < minX ? item.x : minX
minY = item.y < minY ? item.y : minY
}
return {
x: minX,
y: minY,
w: maxX - minX,
h: maxY - minY
}
}
// http://www.geeksforgeeks.org/convex-hull-set-1-jarviss-algorithm-or-wrapping/
// To find orientation of ordered triplet (p, q, r).
// The function returns following values
// 0 --> p, q and r are colinear
// 1 --> Clockwise
// 2 --> Counterclockwise
function orientation(p, q, r) {
var val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
if (val == 0) return 0; // collinear
return (val > 0) ? 1 : 2; // clock or counterclock wise
}
function convexHull(points, n) {
// There must be at least 3 points
if (n < 3) return;
// Initialize Result
var hull = [];
// Find the leftmost point
var l = 0;
for (var i = 1; i < n; i++) {
if (points[i].x < points[l].x) {
l = i;
}
}
// Start from leftmost point, keep moving
// counterclockwise until reach the start point
// again. This loop runs O(h) times where h is
// number of points in result or output.
var p = l, q;
do {
// Add current point to result
// Prevent duplicates object
// if (hull.findIndex(i => i.x == points[p].x && i.y == points[p].y)==-1){
hull.push(points[p]);
// }
// Search for a point 'q' such that
// orientation(p, x, q) is counterclockwise
// for all points 'x'. The idea is to keep
// track of last visited most counterclock-
// wise point in q. If any point 'i' is more
// counterclock-wise than q, then update q.
q = (p + 1) % n;
for (var i = 0; i < n; i++) {
// If i is more counterclockwise than
// current q, then update q
if (orientation(points[p], points[i], points[q]) == 2)
q = i;
}
// Now q is the most counterclockwise with
// respect to p. Set p as q for next iteration,
// so that q is added to result 'hull'
p = q;
} while (p != l); // While we don't come to first
// point
// Print Result
// for (var i in hull) {
// var temp = hull[i]
// console.log("(" + temp.x + ", " + temp.y + ")");
// }
return hull
}
function drawImageWithDegree(canvasId, path, width, height, degree) {
let ctx = wx.createCanvasContext(canvasId)
let isVertical = degree % 180 > 0
let drawWidth = isVertical ? height : width
let drawHeight = isVertical ? width : height
let centerX = width / 2
let cneterY = height / 2
let drawCenterX = drawWidth / 2
let drawCneterY = drawHeight / 2
let d = Math.abs(width-height)/2
// ctx.translate(drawCenterX, drawCneterY)
// ctx.rotate(degree * Math.PI / 180)
// ctx.translate(-drawCenterX, -drawCneterY)
ctx.translate(centerX, cneterY)
ctx.rotate(degree * Math.PI / 180)
ctx.translate(-centerX, -cneterY)
// ctx.translate(-d, d)
if (isVertical) {
if (drawHeight > drawWidth) {
ctx.drawImage(path, d, -d, drawWidth, drawHeight)
}
else {
ctx.drawImage(path, -d, d, drawWidth, drawHeight)
}
}
else {
ctx.drawImage(path, 0, 0, drawWidth, drawHeight)
}
ctx.draw(false, function (e) {
console.log('draw callback')
})
}
// 获取适应屏幕的图片显示大小
const getAdjustSize = (W, H, width, height) => {
if (width > W) {
height = W / width * height
width = W
}
if (height > H) {
width = H / height * width
height = H
}
return {
width: width,
height: height
}
}
const cropperUtil = {
getCropRect,
getAdjustSize,
convexHull,
drawImageWithDegree
}
export default class MyPage extends wepy.component {
props = {
params:{
type:Object,
default:{
src:'',
mode:"rectangle",
sizeType:["compressed"],
visable:false
},
twoWay: true,
}
}
customData = {} // 自定义数据
customFunction() {
} // 自定义方法
onLoad(options) {
this.init(W, H)
} // 在Page和Component共用的生命周期函数
onShow() {
} // 只在Page中存在的页面生命周期函数
config = {}; // 只在Page实例中存在的配置数据,对应于原生的page.json文件
data = {
cropperData:{},
cropperMovableItems:{},
cropperChangableData:{}
}; // 页面所需数据均需在这里声明,可用于模板数据绑定
components = {}; // 声明页面中所引用的组件,或声明组件中所引用的子组件
mixins = []; // 声明页面所引用的Mixin实例
computed = {}; // 声明计算属性(详见后文介绍)
watch = {
params(newVal){
newVal.mode=newVal.mode?newVal.mode:'rectangle';
newVal.sizeType=newVal.sizeType?newVal.sizeType:['compressed'];
newVal.visable=newVal.visable?newVal.visable:false;
this.showCropper(newVal);
}
}; // 声明数据watcher(详见后文介绍)
methods = {
// moveable-view touchmove
moveEvent(key,e){
let originalSize = this.cropperChangableData.originalSize
this.setupMoveItem(key, e.changedTouches, {
path: this.cropperData.imageInfo.path,
width: originalSize.width,
height: originalSize.height
})
},
// moveable-view touchend,end的时候设置movable-view的位置,如果在move阶段设置位置,选中会不流畅
endEvent(key,e){
let cropperData = this.cropperData
let cropperMovableItems = this.cropperMovableItems
let cropperChangableData = this.cropperChangableData
let originalSize = cropperChangableData.originalSize
this.setupMoveItem(key, e.changedTouches, {
path: this.cropperData.imageInfo.path,
width: originalSize.width,
height: originalSize.height
}, (cropperMovableItems, canCrop) => {
cropperChangableData.canCrop = canCrop
this.cropperChangableData=cropperChangableData;
this.cropperMovableItems= cropperMovableItems;
this.$apply();
})
},
// 隐藏cropper
hideCropper(){
this.params.visable = false
this.cropperData.cropCallback = null
this.cropperData=this.data.cropperData,
this.cropperMovableItems= {
topleft: {
x: -1,
y: -1
},
topright: {
x: -1,
y: -1
},
bottomleft: {
x: -1,
y: -1
},
bottomright: {
x: -1,
y: -1
}
},
this.cropperChangableData= {
canCrop: true,
rotateDegree: 0
}
this.clearCanvas(this.cropperData.imageInfo)
this.$emit("wepyCropperCancle");
},
// 旋转图片
rotateImage(){
let imageInfo = this.data.cropperData.imageInfo
let width = imageInfo.width
let height = imageInfo.height
let rotateDegree = this.cropperChangableData.rotateDegree
rotateDegree = rotateDegree == 360 ? 90 : rotateDegree + 90
// 判断是否为垂直方向
let isVertical = rotateDegree % 180 > 0
let rotateWidth = isVertical ? height : width
let rotateHeight = isVertical ? width : height
let size = cropperUtil.getAdjustSize(W, H, rotateWidth, rotateHeight)
// 适应屏幕的位置
let left = (W - size.width) / 2
let top = (H - size.height) / 2
let cropperData = this.cropperData
cropperData.left = left
cropperData.top = top
let cropperChangableData = this.cropperChangableData
cropperChangableData.originalSize = {
width: rotateWidth,
height: rotateHeight
}
cropperChangableData.scaleSize = {
width: size.width,
height: size.height
}
cropperChangableData.rotateDegree = rotateDegree
this.cropperChangableData=cropperChangableData;
this.cropperData= cropperData;
let cropperMovableItemsCopy = this.cropperMovableItems
let cropperMovableItems = {
topleft: {
x: 0,
y: 0
},
topright: {
x: 0,
y: 0
},
bottomleft: {
x: 0,
y: 0
},
bottomright: {
x: 0,
y: 0
}
}
this.cropperMovableItems= cropperMovableItems;
var that=this;
setTimeout(() => {
that.loadImage(imageInfo.path, rotateWidth, rotateHeight, true)
// that.setData({
// cropperMovableItems: cropperMovableItemsCopy
// })
}, 100)
},
// 原图按钮被点击
originalChange(){
let imageInfo = this.cropperData.imageInfo
let originalSize = this.cropperChangableData.originalSize
let width = originalSize.width
let height = originalSize.height
let original = !this.cropperData.original
let compressedScale = original ? 1.0 : 0.4
let size = cropperUtil.getAdjustSize(W, H, width, height)
console.log("change original=" + original)
this.cropperData.original = original
this.cropperData.scaleInfo = {
x: width * compressedScale / size.width,
y: height * compressedScale / size.height
}
// 之所以要设置cropperMovableItems,然后延时在设置一次,是因为改变cropperData后,movable-view会莫名其妙移动到左上角
let cropperMovableItemsCopy = this.cropperMovableItems
let cropperMovableItems = {
topleft: {
x: 0,
y: 0
},
topright: {
x: 0,
y: 0
},
bottomleft: {
x: 0,
y: 0
},
bottomright: {
x: 0,
y: 0
}
}
this.cropperDat=this.cropperData;
this.cropperMovableItems=cropperMovableItems;
var that=this;
setTimeout(() => {
that.cropperMovableItems=cropperMovableItemsCopy;
that.$apply();
}, 100)
this.$apply();
this.drawOriginalImage()
},
// 截取选中图片,如果有回调,则调用
cropImage(){
let cropperData = this.cropperData
let mode = cropperData.mode
let scaleInfo = cropperData.scaleInfo
let width = cropperData.width
let height = cropperData.height
let cropperMovableItems = this.cropperMovableItems
if (mode == 'rectangle') {
let maxX = 0, maxY = 0
for (let key in cropperMovableItems) {
let item = cropperMovableItems[key]
maxX = item.x > maxX ? item.x : maxX
maxY = item.y > maxY ? item.y : maxY
}
let minX = maxX, minY = maxY
for (let key in cropperMovableItems) {
let item = cropperMovableItems[key]
minX = item.x < minX ? item.x : minX
minY = item.y < minY ? item.y : minY
}
let w = maxX - minX, h = maxY - minY
w *= scaleInfo.x
h *= scaleInfo.y
let x = minX * scaleInfo.x, y = minY * scaleInfo.y
console.log('crop rect: x=' + x + ',y=' + y + ',w=' + w + ',h=' + h)
let ctx = wx.createCanvasContext("originalCanvas")
wx.showLoading({
title: '正在截取...',
})
wx.canvasToTempFilePath({
x: x,
y: y,
width: w,
height: h,
destWidth: w,
destHeight: h,
canvasId: 'originalCanvas',
success: (res) =>{
let tempFilePath = res.tempFilePath
wx.hideLoading()
this.params.visable=false;
this.$apply();
this.$emit("wepyCropperFinsh",tempFilePath);
},
fail(res) {
console.log("fail res:")
console.log(res)
}
})
}
else {
let res = [[0, 0], [0, 0], [0, 0], [0, 0]]
let points = []
for (let key in cropperMovableItems) {
let x = Math.ceil(cropperMovableItems[key].x * scaleInfo.x)
let y = Math.ceil(cropperMovableItems[key].y * scaleInfo.y)
let index = 0
if (key == 'topleft') {
index = 0
}
else if (key == 'bottomleft') {
index = 1
}
else if (key == 'bottomright') {
index = 2
}
else if (key == 'topright') {
index = 3
}
res[index] = [x, y]
points.push({ x, y })
}
cropperUtil.convexHull(points, points.length)
this.params.visable=false;
this.$apply();
this.$emit("wepyCropperFinsh",res);
}
}
}; // 声明页面wxml中标签的事件处理函数。注意,此处只用于声明页面wxml中标签的bind、catch事件,自定义方法需以自定义方法的方式声明
events = {
}; // 声明组件之间的事件处理函数
init(W, H) {
this.cropperData={
hidden: true,
left: 0,
top: 0,
width: W,
height: H,
itemLength: 50,
imageInfo: {
path: '',
width: 0,
height: 0
},
scaleInfo: {
x: 1,
y: 1
},
cropCallback: null,
sizeType: ['original', 'compressed'], //'original'(default) | 'compressed'
original: false, // 默认压缩,压缩比例为截图的0.4
mode: 'quadrangle', //默认矩形
}
this.cropperMovableItems={
topleft: {
x: 50,
y: 50
},
topright: {
x: W - 50,
y: 50
},
bottomleft: {
x: 50,
y: H - 50
},
bottomright: {
x: W - 50,
y: H - 50
}
}
this.cropperChangableData={
canCrop: true,
rotateDegree: 0,
originalSize: {
width: 0,
height: 0
},
scaleSize: {
width: 0,
height: 0
}
}
}
// 显示cropper,如果有图片则载入
showCropper(options){
let src = options.src
let callback = options.callback
let sizeType = options.sizeType
let mode = options.mode
let filterType = []
if (sizeType.indexOf('original') > -1) {
filterType.push('original')
}
if (sizeType.indexOf('compressed') > -1) {
filterType.push('compressed')
}
if (filterType.length == 1 && filterType.indexOf('original') > -1) {
this.cropperData.original = true
}
if (mode) {
this.cropperData.mode = mode
}
this.cropperData.cropCallback = callback
this.cropperData.sizeType = filterType
this.$apply();
if (src) {
wx.getImageInfo({
src: src,
success: (res) =>{
var w = res.width, h = res.height
this.loadImage(src, w, h, false)
}
})
}
}
// 测试
// 根据图片大小设置canvas大小,并绘制图片
loadImage(src, width, height, isRotate){
let size = cropperUtil.getAdjustSize(W, H, width, height)
// 适应屏幕的位置
let left = (W - size.width) / 2
let top = (H - size.height) / 2
// set data
let updateData = {}
let cropperData = this.cropperData
if (!isRotate) {
cropperData.imageInfo = {
path: src,
width: width,
height: height
}
}
cropperData.left = left
cropperData.top = top
cropperData.width = size.width
cropperData.height = size.height
let compressedScale = this.cropperData.original ? 1.0 : 0.4
// let scaleSize = cropperUtil.getAdjustSize(W, H, width, height)
cropperData.scaleInfo = {
x: width * compressedScale / size.width,
y: height * compressedScale / size.height
}
updateData.cropperData = cropperData
updateData.cropperMovableItems = {
topleft: {
x: 50,
y: 50
},
topright: {
x: size.width - 50,
y: 50
},
bottomleft: {
x: 50,
y: size.height - 50
},
bottomright: {
x: size.width - 50,
y: size.height - 50
}
}
let cropperChangableData = this.cropperChangableData
cropperChangableData.originalSize = {
width: width,
height: height
}
cropperChangableData.scaleSize = {
width: size.width,
height: size.height
}
updateData.cropperChangableData = cropperChangableData
this.cropperData=updateData.cropperData;
this.cropperMovableItems=updateData.cropperMovableItems;
// console.log("loadImage size:" + width + "*" + height)
this.drawImage({
path: this.cropperData.imageInfo.path,
width: width,
height: height
})
// that.drawImage(that.data.cropperData.imageInfo)
this.drawLines(this.cropperMovableItems, this.cropperData.imageInfo)
}
// 清空canvas上的数据
clearCanvas(imageInfo){
let cropperData = this.cropperData
let size = cropperUtil.getAdjustSize(W, H, imageInfo.width, imageInfo.height)
if (imageInfo.path != '') {
let compressedScale = this.cropperData.original ? 1.0 : 0.4
//清空原图
let ctx = wx.createCanvasContext("originalCanvas")
ctx.clearRect(0, 0, imageInfo.width * compressedScale, imageInfo.height * compressedScale)
ctx.draw()
//清空选择区图片
let canvas = wx.createCanvasContext("canvas")
canvas.clearRect(0, 0, size.width, size.height)
canvas.draw()
// 清空白线框
let moveCanvas = wx.createCanvasContext("moveCanvas")
moveCanvas.clearRect(0, 0, size.width, size.height)
moveCanvas.draw()
}
}
//绘制图片
drawImage(imageInfo){
let cropperData = this.cropperData
let size = cropperUtil.getAdjustSize(W, H, imageInfo.width, imageInfo.height)
if (imageInfo.path != '') {
let path = imageInfo.path
let compressedScale = this.cropperData.original ? 1.0 : 0.4
let rotateDegree = this.cropperChangableData.rotateDegree
//绘制原图
cropperUtil.drawImageWithDegree(
"originalCanvas",
path,
imageInfo.width * compressedScale,
imageInfo.height * compressedScale,
rotateDegree
)
// let originalCanvas = wx.createCanvasContext("originalCanvas")
// originalCanvas.drawImage(path, 0, 0, imageInfo.width * compressedScale, imageInfo.height * compressedScale)
// originalCanvas.draw()
//绘制选择区图片
cropperUtil.drawImageWithDegree("canvas", path, size.width, size.height, rotateDegree)
// let canvas = wx.createCanvasContext("canvas")
// canvas.drawImage(path, 0, 0, size.width, size.height)
// canvas.draw()
this.$apply();
console.log("draw=" + path)
}
}
// 单独绘制原图,当切换原图与非原图时使用
drawOriginalImage(){
let cropperData = this.cropperData
let imageInfo = cropperData.imageInfo
let originalSize = this.cropperChangableData.originalSize
if (imageInfo.path != '') {
let path = imageInfo.path
let compressedScale = this.cropperData.original ? 1.0 : 0.4
let rotateDegree = this.cropperChangableData.rotateDegree
//绘制原图
cropperUtil.drawImageWithDegree(
"originalCanvas",
path,
originalSize.width * compressedScale,
originalSize.height * compressedScale,
rotateDegree
)
// let originalCanvas = wx.createCanvasContext("originalCanvas")
// originalCanvas.drawImage(path, 0, 0, imageInfo.width * compressedScale, imageInfo.height * compressedScale)
// originalCanvas.draw()
}
}
//绘制选框
drawLines(cropperMovableItems, imageInfo, callback){
let cropperData = this.cropperData
let mode = cropperData.mode
let rotateDegree = this.cropperChangableData.rotateDegree
let size
if (rotateDegree % 180 > 0) {
size = cropperUtil.getAdjustSize(W, H, imageInfo.height, imageInfo.width)
} else {
size = cropperUtil.getAdjustSize(W, H, imageInfo.width, imageInfo.height)
}
let convexDots = []
let orderedDots = []
orderedDots.push(cropperMovableItems['topleft'])
orderedDots.push(cropperMovableItems['topright'])
orderedDots.push(cropperMovableItems['bottomright'])
orderedDots.push(cropperMovableItems['bottomleft'])
// 获取凸边形的点
convexDots = cropperUtil.convexHull(orderedDots, orderedDots.length)
// 四个点组成的四边形是不是凸四边形
let canCrop = convexDots.length == 4
if (callback) {
callback(canCrop)
}
let ctx = wx.createCanvasContext("moveCanvas")
//绘制高亮选中区域
let rect = cropperUtil.getCropRect(convexDots)
if (mode == 'rectangle') {
// 绘制半透明遮罩
ctx.setFillStyle('rgba(0,0,0,0.5)')
ctx.fillRect(0, 0, size.width, size.height)
// 清除选中区域的半透明遮罩,使选中区域高亮
ctx.setFillStyle('rgba(0,0,0,0)')
ctx.clearRect(rect.x, rect.y, rect.w, rect.h)
//绘制选中边框
ctx.setStrokeStyle('white')
ctx.setLineWidth(2)
ctx.beginPath()
ctx.moveTo(rect.x, rect.y)
ctx.lineTo(rect.x + rect.w, rect.y)
ctx.lineTo(rect.x + rect.w, rect.y + rect.h)
ctx.lineTo(rect.x, rect.y + rect.h)
ctx.lineTo(rect.x, rect.y)
ctx.stroke()
ctx.closePath()
}
else {
//绘制选中边框
// 如果四个点组成的四边形不是凸四边形,则显示红色,表示不可取
let color = canCrop ? 'white' : 'red'
ctx.setStrokeStyle(color)
ctx.setLineWidth(2)
ctx.beginPath()
for (let i = 0, len = convexDots.length; i < len; i++) {
let dot = convexDots[i]
if (i == 0) {
ctx.moveTo(dot.x, dot.y)
}
else {
ctx.lineTo(dot.x, dot.y)
}
}
let dot = convexDots[0]
ctx.lineTo(dot.x, dot.y)
ctx.stroke()
ctx.closePath()
}
//绘制四个角
let cornerType = mode == 'rectangle' ? 'rect' : 'circle'
ctx.setFillStyle('white')
ctx.setStrokeStyle('white')
// 绘制不同样式的角
if (cornerType == 'circle') {
for (let i = 0, len = orderedDots.length; i < len; i++) {
let dot = orderedDots[i]
ctx.beginPath()
ctx.arc(dot.x, dot.y, 10, 0, 2 * Math.PI, true)
ctx.fill()
ctx.closePath()
}
}
else if (cornerType == 'rect') {
let len = 20, w = 3.0, offset = w / 2.0
ctx.setLineWidth(w)
ctx.beginPath()
ctx.moveTo(rect.x - offset, rect.y - offset + len)
ctx.lineTo(rect.x - offset, rect.y - offset)
ctx.lineTo(rect.x - offset + len, rect.y - offset)
ctx.moveTo(rect.x + offset + rect.w - len, rect.y - offset)
ctx.lineTo(rect.x + offset + rect.w, rect.y - offset)
ctx.lineTo(rect.x + offset + rect.w, rect.y - offset + len)
ctx.moveTo(rect.x + offset + rect.w, rect.y + offset + rect.h - len)
ctx.lineTo(rect.x + offset + rect.w, rect.y + offset + rect.h)
ctx.lineTo(rect.x + offset + rect.w - len, rect.y + offset + rect.h)
ctx.moveTo(rect.x - offset, rect.y + offset + rect.h - len)
ctx.lineTo(rect.x - offset, rect.y + offset + rect.h)
ctx.lineTo(rect.x - offset + len, rect.y + offset + rect.h)
ctx.stroke()
ctx.closePath()
}
ctx.draw()
}
// move events
setupMoveItem(key, changedTouches, imageInfo, callback){
let cropperData = this.cropperData
let cropperMovableItems = this.cropperMovableItems
let left = cropperData.left
let top = cropperData.top
let mode = cropperData.mode
let size = cropperUtil.getAdjustSize(W, H, imageInfo.width, imageInfo.height)
if (changedTouches.length == 1) {
let touch = changedTouches[0]
let x = touch.clientX
let y = touch.clientY
// 相对画布的点
x = x - left
y = y - top
cropperMovableItems[key].x = x
cropperMovableItems[key].y = y
// 边界检测,使截图不超出截图区域
x = x < 0 ? 0 : (x > size.width ? size.width : x)
y = y < 0 ? 0 : (y > size.height ? size.height : y)
cropperMovableItems[key].x = x
cropperMovableItems[key].y = y
// 如果是在矩形模式下
if (mode == 'rectangle') {
// 同时设置相连两个点的位置,是相邻的两个点跟随着移动点动,保证选框为矩形
if (key == 'topleft') {
cropperMovableItems['bottomleft'].x = x
cropperMovableItems['topright'].y = y
}
else if (key == 'topright') {
cropperMovableItems['bottomright'].x = x
cropperMovableItems['topleft'].y = y
}
else if (key == 'bottomleft') {
cropperMovableItems['topleft'].x = x
cropperMovableItems['bottomright'].y = y
}
else if (key == 'bottomright') {
cropperMovableItems['topright'].x = x
cropperMovableItems['bottomleft'].y = y
}
}
this.drawLines(cropperMovableItems, imageInfo, function (canCrop) {
if (callback) {
callback(cropperMovableItems, canCrop)
}
})
}
}
}
</script>
<style lang="scss" src="wepy-cropper.scss"></style>