tui-picture-cropper.vue 17 KB

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