tui-picture-cropper.vue 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  1. <template>
  2. <view class="tui-container" @touchmove.stop.prevent="stop">
  3. <view
  4. class="tui-image-cropper"
  5. :change:prop="parse.propsChange"
  6. :prop="props"
  7. :data-lockRatio="lockRatio"
  8. :data-lockWidth="lockWidth"
  9. :data-lockHeight="lockHeight"
  10. :data-maxWidth="maxWidth"
  11. :data-minWidth="minWidth"
  12. :data-maxHeight="maxHeight"
  13. :data-minHeight="minHeight"
  14. :data-width="width"
  15. :data-height="height"
  16. :data-limitMove="limitMove"
  17. :data-windowHeight="sysInfo.windowHeight || 600"
  18. :data-windowWidth="sysInfo.windowWidth || 400"
  19. :data-imgTop="imgTop"
  20. :data-imgLeft="imgLeft"
  21. :data-imgWidth="imgWidth"
  22. :data-imgHeight="imgHeight"
  23. :data-angle="angle"
  24. @touchend="parse.cutTouchEnd"
  25. @touchstart="parse.cutTouchStart"
  26. @touchmove="parse.cutTouchMove"
  27. >
  28. <view class="tui-content">
  29. <view class="tui-content-top tui-bg-transparent" :style="{ transitionProperty: cutAnimation ? '' : 'background' }"></view>
  30. <view class="tui-content-middle">
  31. <view class="tui-bg-transparent tui-wxs-bg" :style="{ transitionProperty: cutAnimation ? '' : 'background' }"></view>
  32. <view class="tui-cropper-box" :style="{ borderColor: borderColor, transitionProperty: cutAnimation ? '' : 'background' }">
  33. <view
  34. v-for="(item, index) in 4"
  35. :key="index"
  36. class="tui-edge"
  37. :class="[`tui-${index < 2 ? 'top' : 'bottom'}-${index === 0 || index === 2 ? 'left' : 'right'}`]"
  38. :style="{
  39. width: edgeWidth,
  40. height: edgeWidth,
  41. borderColor: edgeColor,
  42. borderWidth: edgeBorderWidth,
  43. left: index === 0 || index === 2 ? `-${edgeOffsets}` : 'auto',
  44. right: index === 1 || index === 3 ? `-${edgeOffsets}` : 'auto',
  45. top: index < 2 ? `-${edgeOffsets}` : 'auto',
  46. bottom: index > 1 ? `-${edgeOffsets}` : 'auto'
  47. }"
  48. ></view>
  49. </view>
  50. <view class="tui-flex-auto tui-bg-transparent" :style="{ transitionProperty: cutAnimation ? '' : 'background' }"></view>
  51. </view>
  52. <view class="tui-flex-auto tui-bg-transparent" :style="{ transitionProperty: cutAnimation ? '' : 'background' }"></view>
  53. </view>
  54. <image
  55. @load="imageLoad"
  56. @error="imageLoad"
  57. @touchstart="parse.touchstart"
  58. @touchmove="parse.touchmove"
  59. @touchend="parse.touchend"
  60. :data-minScale="minScale"
  61. :data-maxScale="maxScale"
  62. :data-disableRotate="disableRotate"
  63. :style="{
  64. width: imgWidth ? imgWidth + 'px' : 'auto',
  65. height: imgHeight ? imgHeight + 'px' : 'auto',
  66. transitionDuration: (cutAnimation ? 0.3 : 0) + 's'
  67. }"
  68. class="tui-cropper-image"
  69. :src="imageUrl"
  70. v-if="imageUrl"
  71. mode="widthFix"
  72. ></image>
  73. </view>
  74. <canvas
  75. canvas-id="tui-image-cropper"
  76. id="tui-image-cropper"
  77. :disable-scroll="true"
  78. :style="{ width: CROPPER_WIDTH * scaleRatio + 'px', height: CROPPER_HEIGHT * scaleRatio + 'px' }"
  79. class="tui-cropper-canvas"
  80. ></canvas>
  81. <view class="tui-cropper-tabbar" v-if="!custom">
  82. <view class="tui-op-btn" @tap.stop="back">取消</view>
  83. <image :src="rotateImg" class="tui-rotate-img" @tap="setAngle"></image>
  84. <view class="tui-op-btn" @tap.stop="getImage">完成</view>
  85. </view>
  86. </view>
  87. </template>
  88. <script src="./tui-picture-cropper.wxs" module="parse" lang="wxs"></script>
  89. <script>
  90. /**
  91. * 注意:组件中使用的图片地址,将文件复制到自己项目中
  92. * 如果图片位置与组件同级,编译成小程序时图片会丢失
  93. * 拷贝static下整个components文件夹
  94. *也可直接转成base64(不建议)
  95. * */
  96. export default {
  97. name: 'tuiPictureCropper',
  98. props: {
  99. //图片路径
  100. imageUrl: {
  101. type: String,
  102. default: ''
  103. },
  104. /*
  105. 默认正方形,可修改大小控制比例
  106. 裁剪框高度 px
  107. */
  108. height: {
  109. type: Number,
  110. default: 280
  111. },
  112. //裁剪框宽度 px
  113. width: {
  114. type: Number,
  115. default: 280
  116. },
  117. //裁剪框最小宽度 px
  118. minWidth: {
  119. type: Number,
  120. default: 100
  121. },
  122. //裁剪框最小高度 px
  123. minHeight: {
  124. type: Number,
  125. default: 100
  126. },
  127. //裁剪框最大宽度 px
  128. maxWidth: {
  129. type: Number,
  130. default: 360
  131. },
  132. //裁剪框最大高度 px
  133. maxHeight: {
  134. type: Number,
  135. default: 360
  136. },
  137. //裁剪框border颜色
  138. borderColor: {
  139. type: String,
  140. default: 'rgba(255,255,255,0.1)'
  141. },
  142. //裁剪框边缘线颜色
  143. edgeColor: {
  144. type: String,
  145. default: '#FFFFFF'
  146. },
  147. //裁剪框边缘线宽度 w=h
  148. edgeWidth: {
  149. type: String,
  150. default: '34rpx'
  151. },
  152. //裁剪框边缘线border宽度
  153. edgeBorderWidth: {
  154. type: String,
  155. default: '6rpx'
  156. },
  157. //偏移距离,根据edgeBorderWidth进行调整
  158. edgeOffsets: {
  159. type: String,
  160. default: '6rpx'
  161. },
  162. /**
  163. * 如果宽度和高度都为true则裁剪框禁止拖动
  164. * 裁剪框宽度锁定
  165. */
  166. lockWidth: {
  167. type: Boolean,
  168. default: false
  169. },
  170. //裁剪框高度锁定
  171. lockHeight: {
  172. type: Boolean,
  173. default: false
  174. },
  175. //锁定裁剪框比例(放大或缩小)
  176. lockRatio: {
  177. type: Boolean,
  178. default: false
  179. },
  180. //生成的图片尺寸相对剪裁框的比例
  181. scaleRatio: {
  182. type: Number,
  183. default: 2
  184. },
  185. //图片的质量,取值范围为 (0, 1],不在范围内时当作1.0处理
  186. quality: {
  187. type: Number,
  188. default: 0.8
  189. },
  190. //图片旋转角度
  191. rotateAngle: {
  192. type: Number,
  193. default: 0
  194. },
  195. //图片最小缩放比
  196. minScale: {
  197. type: Number,
  198. default: 0.5
  199. },
  200. //图片最大缩放比
  201. maxScale: {
  202. type: Number,
  203. default: 2
  204. },
  205. //是否禁用触摸旋转(为false则可以触摸转动图片,limitMove为false生效)
  206. disableRotate: {
  207. type: Boolean,
  208. default: true
  209. },
  210. //是否限制移动范围(剪裁框只能在图片内,为true不可触摸转动图片)
  211. limitMove: {
  212. type: Boolean,
  213. default: true
  214. },
  215. //自定义操作栏(为true时隐藏底部操作栏)
  216. custom: {
  217. type: Boolean,
  218. default: false
  219. },
  220. //值发生改变开始裁剪(custom为true时生效)
  221. startCutting: {
  222. type: [Number, Boolean],
  223. default: 0
  224. },
  225. /**
  226. * 是否返回base64(H5端默认base64)
  227. * 支持平台:App,微信小程序,支付宝小程序,H5(默认url就是base64)
  228. **/
  229. isBase64: {
  230. type: Boolean,
  231. default: false
  232. },
  233. //裁剪时是否显示loadding
  234. loadding: {
  235. type: Boolean,
  236. default: true
  237. },
  238. //旋转icon
  239. rotateImg: {
  240. type: String,
  241. default: '/static/components/cropper/img_rotate.png'
  242. }
  243. },
  244. data() {
  245. return {
  246. TIME_CUT_CENTER: null,
  247. CROPPER_WIDTH: 200, //裁剪框宽
  248. CROPPER_HEIGHT: 200, //裁剪框高
  249. cutX: 0, //画布x轴起点
  250. cutY: 0, //画布y轴起点0
  251. canvasWidth: 0,
  252. canvasHeight: 0,
  253. imgWidth: 0, //图片宽度
  254. imgHeight: 0, //图片高度
  255. scale: 1, //图片缩放比
  256. angle: 0, //图片旋转角度
  257. cutAnimation: false, //是否开启图片和裁剪框过渡
  258. cutAnimationTime: null,
  259. imgTop: 0, //图片上边距
  260. imgLeft: 0, //图片左边距
  261. ctx: null,
  262. sysInfo: {},
  263. props: '',
  264. sizeChange: 0, //2
  265. angleChange: 0, //3
  266. resetChange: 0, //4
  267. centerChange: 0 //5
  268. };
  269. },
  270. watch: {
  271. //定义变量然后利用change触发
  272. imageUrl(val, oldVal) {
  273. this.imageReset();
  274. this.showLoading();
  275. uni.getImageInfo({
  276. src: val,
  277. success: res => {
  278. //计算图片尺寸
  279. this.imgComputeSize(res.width, res.height);
  280. if (this.limitMove) {
  281. this.angleChange++;
  282. this.props = `3,${this.angleChange}`;
  283. }
  284. },
  285. fail: err => {
  286. this.imgComputeSize();
  287. if (this.limitMove) {
  288. this.angleChange++;
  289. this.props = `3,${this.angleChange}`;
  290. }
  291. }
  292. });
  293. },
  294. rotateAngle(val) {
  295. this.cutAnimation = true;
  296. this.angle = val;
  297. this.angleChanged(val);
  298. },
  299. cutAnimation(val) {
  300. //开启过渡260毫秒之后自动关闭
  301. clearTimeout(this.cutAnimationTime);
  302. if (val) {
  303. this.cutAnimationTime = setTimeout(() => {
  304. this.cutAnimation = false;
  305. }, 260);
  306. }
  307. },
  308. limitMove(val) {
  309. if (val) {
  310. this.angleChanged(this.angle);
  311. }
  312. },
  313. startCutting(val) {
  314. if (this.custom && val) {
  315. this.getImage();
  316. }
  317. }
  318. },
  319. mounted() {
  320. this.sysInfo = uni.getSystemInfoSync();
  321. this.imgTop = this.sysInfo.windowHeight / 2;
  322. this.imgLeft = this.sysInfo.windowWidth / 2;
  323. this.CROPPER_WIDTH = this.width;
  324. this.CROPPER_HEIGHT = this.height;
  325. this.canvasHeight = this.height;
  326. this.canvasWidth = this.width;
  327. this.ctx = uni.createCanvasContext('tui-image-cropper', this);
  328. //初始化
  329. setTimeout(() => {
  330. this.props = '1,1';
  331. }, 0);
  332. setTimeout(() => {
  333. this.$emit('ready', {});
  334. }, 200);
  335. },
  336. methods: {
  337. //返回裁剪后图片信息
  338. getImage() {
  339. if (!this.imageUrl) {
  340. uni.showToast({
  341. title: '请选择图片',
  342. icon: 'none'
  343. });
  344. return;
  345. }
  346. this.loadding && this.showLoading();
  347. let draw = () => {
  348. //图片实际大小
  349. let imgWidth = this.imgWidth * this.scale * this.scaleRatio;
  350. let imgHeight = this.imgHeight * this.scale * this.scaleRatio;
  351. //canvas和图片的相对距离
  352. let xpos = this.imgLeft - this.cutX;
  353. let ypos = this.imgTop - this.cutY;
  354. //旋转画布
  355. this.ctx.translate(xpos * this.scaleRatio, ypos * this.scaleRatio);
  356. this.ctx.rotate((this.angle * Math.PI) / 180);
  357. this.ctx.drawImage(this.imageUrl, -imgWidth / 2, -imgHeight / 2, imgWidth, imgHeight);
  358. this.ctx.draw(false, () => {
  359. let params = {
  360. width: this.canvasWidth * this.scaleRatio,
  361. height: Math.round(this.canvasHeight * this.scaleRatio),
  362. destWidth: this.canvasWidth * this.scaleRatio,
  363. destHeight: Math.round(this.canvasHeight) * this.scaleRatio,
  364. fileType: 'png',
  365. quality: this.quality
  366. };
  367. let data = {
  368. url: '',
  369. base64: '',
  370. width: this.canvasWidth * this.scaleRatio,
  371. height: this.canvasHeight * this.scaleRatio
  372. };
  373. // #ifdef MP-ALIPAY
  374. if (this.isBase64) {
  375. this.ctx.toDataURL(params).then(dataURL => {
  376. data.base64 = dataURL;
  377. this.loadding && uni.hideLoading();
  378. this.$emit('cropper', data);
  379. });
  380. } else {
  381. this.ctx.toTempFilePath({
  382. ...params,
  383. success: res => {
  384. data.url = res.tempFilePath;
  385. this.loadding && uni.hideLoading();
  386. this.$emit('cropper', data);
  387. }
  388. });
  389. }
  390. // #endif
  391. // #ifndef MP-ALIPAY
  392. // #ifdef MP-BAIDU || MP-TOUTIAO || H5
  393. this.isBase64 = false;
  394. // #endif
  395. if (this.isBase64) {
  396. uni.canvasGetImageData({
  397. canvasId: 'tui-image-cropper',
  398. x: 0,
  399. y: 0,
  400. width: this.canvasWidth * this.scaleRatio,
  401. height: Math.round(this.canvasHeight * this.scaleRatio),
  402. success: res => {
  403. const arrayBuffer = new Uint8Array(res.data);
  404. const base64 = uni.arrayBufferToBase64(arrayBuffer);
  405. data.base64 = base64;
  406. this.loadding && uni.hideLoading();
  407. this.$emit('cropper', data);
  408. }
  409. });
  410. } else {
  411. uni.canvasToTempFilePath(
  412. {
  413. ...params,
  414. canvasId: 'tui-image-cropper',
  415. success: res => {
  416. data.url = res.tempFilePath;
  417. // #ifdef H5
  418. data.base64 = res.tempFilePath;
  419. // #endif
  420. this.loadding && uni.hideLoading();
  421. this.$emit('cropper', data);
  422. },
  423. fail(res) {
  424. console.log(res);
  425. }
  426. },
  427. this
  428. );
  429. }
  430. // #endif
  431. });
  432. };
  433. if (this.CROPPER_WIDTH != this.canvasWidth || this.CROPPER_HEIGHT != this.canvasHeight) {
  434. this.CROPPER_WIDTH = this.canvasWidth;
  435. this.CROPPER_HEIGHT = this.canvasHeight;
  436. this.$nextTick(() => {
  437. this.ctx.draw();
  438. setTimeout(() => {
  439. draw();
  440. }, 100);
  441. });
  442. } else {
  443. draw();
  444. }
  445. },
  446. change(e) {
  447. this.cutX = e.cutX || 0;
  448. this.cutY = e.cutY || 0;
  449. this.canvasWidth = e.canvasWidth || 100;
  450. this.canvasHeight = e.canvasHeight || 100;
  451. this.imgWidth = e.imgWidth || 100;
  452. this.imgHeight = e.imgHeight || 100;
  453. this.scale = e.scale || 1;
  454. this.angle = e.angle || 0;
  455. this.imgTop = e.imgTop || 0;
  456. this.imgLeft = e.imgLeft || 0;
  457. },
  458. imageReset() {
  459. this.scale = 1;
  460. this.angle = 0;
  461. let sys = this.sysInfo.windowHeight ? this.sysInfo : uni.getSystemInfoSync();
  462. this.imgTop = sys.windowHeight / 2;
  463. this.imgLeft = sys.windowWidth / 2;
  464. this.resetChange++;
  465. this.props = `4,${this.resetChange}`;
  466. //初始化旋转角度 0deg
  467. this.$emit('initAngle', {});
  468. },
  469. imageLoad(e) {
  470. this.imageReset();
  471. uni.hideLoading();
  472. this.$emit('imageLoad', {});
  473. },
  474. imgComputeSize(width, height) {
  475. //默认按图片最小边 = 对应裁剪框尺寸
  476. let imgWidth = width,
  477. imgHeight = height;
  478. if (imgWidth && imgHeight) {
  479. if (imgWidth / imgHeight > this.width / this.height) {
  480. imgHeight = this.height;
  481. imgWidth = (width / height) * imgHeight;
  482. } else {
  483. imgWidth = this.width;
  484. imgHeight = (height / width) * imgWidth;
  485. }
  486. } else {
  487. let sys = this.sysInfo || uni.getSystemInfoSync();
  488. imgWidth = sys.windowWidth;
  489. imgHeight = 0;
  490. }
  491. this.imgWidth = imgWidth;
  492. this.imgHeight = imgHeight;
  493. this.sizeChange++;
  494. this.props = `2,${this.sizeChange}`;
  495. },
  496. moveStop() {
  497. clearTimeout(this.TIME_CUT_CENTER);
  498. this.TIME_CUT_CENTER = setTimeout(() => {
  499. if (!this.cutAnimation) {
  500. this.cutAnimation = true;
  501. }
  502. this.centerChange++;
  503. this.props = `5,${this.centerChange}`;
  504. }, 666);
  505. },
  506. moveDuring() {
  507. clearTimeout(this.TIME_CUT_CENTER);
  508. },
  509. showLoading() {
  510. uni.showLoading({
  511. title: '请稍候...',
  512. mask: true
  513. });
  514. },
  515. stop() {},
  516. back() {
  517. uni.navigateBack();
  518. },
  519. angleChanged(val) {
  520. this.moveStop();
  521. if (this.limitMove && val % 90) {
  522. this.angle = Math.round(val / 90) * 90;
  523. }
  524. this.angleChange++;
  525. this.props = `3,${this.angleChange}`;
  526. },
  527. setAngle() {
  528. this.cutAnimation = true;
  529. this.angle = this.angle + 90;
  530. this.angleChanged(this.angle);
  531. }
  532. }
  533. };
  534. </script>
  535. <style scoped>
  536. .tui-container {
  537. width: 100vw;
  538. height: 100vh;
  539. background-color: rgba(0, 0, 0, 0.6);
  540. position: fixed;
  541. top: 0;
  542. left: 0;
  543. z-index: 1;
  544. }
  545. .tui-image-cropper {
  546. width: 100vw;
  547. height: 100vh;
  548. position: absolute;
  549. }
  550. .tui-content {
  551. width: 100vw;
  552. height: 100vh;
  553. position: absolute;
  554. z-index: 9;
  555. display: flex;
  556. flex-direction: column;
  557. pointer-events: none;
  558. }
  559. .tui-bg-transparent {
  560. background-color: rgba(0, 0, 0, 0.6);
  561. transition-duration: 0.3s;
  562. }
  563. .tui-content-top {
  564. pointer-events: none;
  565. }
  566. .tui-content-middle {
  567. width: 100%;
  568. height: 200px;
  569. display: flex;
  570. box-sizing: border-box;
  571. }
  572. .tui-cropper-box {
  573. position: relative;
  574. /* transition-duration: 0.2s; */
  575. border-style: solid;
  576. border-width: 1rpx;
  577. box-sizing: border-box;
  578. }
  579. .tui-flex-auto {
  580. flex: auto;
  581. }
  582. .tui-cropper-image {
  583. width: 100%;
  584. border-style: none;
  585. position: absolute;
  586. top: 0;
  587. left: 0;
  588. z-index: 2;
  589. -webkit-backface-visibility: hidden;
  590. backface-visibility: hidden;
  591. transform-origin: center;
  592. }
  593. .tui-cropper-canvas {
  594. position: fixed;
  595. z-index: 10;
  596. left: -2000px;
  597. top: -2000px;
  598. pointer-events: none;
  599. }
  600. .tui-edge {
  601. border-style: solid;
  602. pointer-events: auto;
  603. position: absolute;
  604. box-sizing: border-box;
  605. }
  606. .tui-top-left {
  607. border-bottom-width: 0 !important;
  608. border-right-width: 0 !important;
  609. }
  610. .tui-top-right {
  611. border-bottom-width: 0 !important;
  612. border-left-width: 0 !important;
  613. }
  614. .tui-bottom-left {
  615. border-top-width: 0 !important;
  616. border-right-width: 0 !important;
  617. }
  618. .tui-bottom-right {
  619. border-top-width: 0 !important;
  620. border-left-width: 0 !important;
  621. }
  622. .tui-cropper-tabbar {
  623. width: 100%;
  624. height: 120rpx;
  625. padding: 0 40rpx;
  626. box-sizing: border-box;
  627. position: fixed;
  628. left: 0;
  629. bottom: 0;
  630. z-index: 99;
  631. display: flex;
  632. align-items: center;
  633. justify-content: space-between;
  634. color: #ffffff;
  635. font-size: 32rpx;
  636. }
  637. .tui-cropper-tabbar::after {
  638. content: ' ';
  639. position: absolute;
  640. top: 0;
  641. right: 0;
  642. left: 0;
  643. border-top: 1rpx solid rgba(255, 255, 255, 0.2);
  644. -webkit-transform: scaleY(0.5) translateZ(0);
  645. transform: scaleY(0.5) translateZ(0);
  646. transform-origin: 0 100%;
  647. }
  648. .tui-op-btn {
  649. height: 80rpx;
  650. display: flex;
  651. align-items: center;
  652. }
  653. .tui-rotate-img {
  654. width: 44rpx;
  655. height: 44rpx;
  656. }
  657. </style>