tui-picture-cropper.vue 16 KB

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