tui-picture-cropper.vue 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699
  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. async getLocalImage(url) {
  339. return await new Promise((resolve, reject) => {
  340. uni.downloadFile({
  341. url: url,
  342. success: res => {
  343. resolve(res.tempFilePath);
  344. },
  345. fail: res => {
  346. reject(false)
  347. }
  348. })
  349. })
  350. },
  351. //返回裁剪后图片信息
  352. getImage() {
  353. if (!this.imageUrl) {
  354. uni.showToast({
  355. title: '请选择图片',
  356. icon: 'none'
  357. });
  358. return;
  359. }
  360. this.loadding && this.showLoading();
  361. let draw =async () => {
  362. //图片实际大小
  363. let imgWidth = this.imgWidth * this.scale * this.scaleRatio;
  364. let imgHeight = this.imgHeight * this.scale * this.scaleRatio;
  365. //canvas和图片的相对距离
  366. let xpos = this.imgLeft - this.cutX;
  367. let ypos = this.imgTop - this.cutY;
  368. //旋转画布
  369. this.ctx.translate(xpos * this.scaleRatio, ypos * this.scaleRatio);
  370. this.ctx.rotate((this.angle * Math.PI) / 180);
  371. let imgUrl = this.imageUrl;
  372. // #ifdef APP-PLUS || MP-WEIXIN
  373. if (~this.imageUrl.indexOf('https:')) {
  374. imgUrl = await this.getLocalImage(this.imageUrl)
  375. }
  376. // #endif
  377. this.ctx.drawImage(imgUrl, -imgWidth / 2, -imgHeight / 2, imgWidth, imgHeight);
  378. this.ctx.draw(false, () => {
  379. let params = {
  380. width: this.canvasWidth * this.scaleRatio,
  381. height: Math.round(this.canvasHeight * this.scaleRatio),
  382. destWidth: this.canvasWidth * this.scaleRatio,
  383. destHeight: Math.round(this.canvasHeight) * this.scaleRatio,
  384. fileType: 'png',
  385. quality: this.quality
  386. };
  387. let data = {
  388. url: '',
  389. base64: '',
  390. width: this.canvasWidth * this.scaleRatio,
  391. height: this.canvasHeight * this.scaleRatio
  392. };
  393. // #ifdef MP-ALIPAY
  394. if (this.isBase64) {
  395. this.ctx.toDataURL(params).then(dataURL => {
  396. data.base64 = dataURL;
  397. this.loadding && uni.hideLoading();
  398. this.$emit('cropper', data);
  399. });
  400. } else {
  401. this.ctx.toTempFilePath({
  402. ...params,
  403. success: res => {
  404. data.url = res.tempFilePath;
  405. this.loadding && uni.hideLoading();
  406. this.$emit('cropper', data);
  407. }
  408. });
  409. }
  410. // #endif
  411. // #ifndef MP-ALIPAY
  412. // #ifdef MP-BAIDU || MP-TOUTIAO || H5
  413. this.isBase64 = false;
  414. // #endif
  415. if (this.isBase64) {
  416. uni.canvasGetImageData({
  417. canvasId: 'tui-image-cropper',
  418. x: 0,
  419. y: 0,
  420. width: this.canvasWidth * this.scaleRatio,
  421. height: Math.round(this.canvasHeight * this.scaleRatio),
  422. success: res => {
  423. const arrayBuffer = new Uint8Array(res.data);
  424. const base64 = uni.arrayBufferToBase64(arrayBuffer);
  425. data.base64 = base64;
  426. this.loadding && uni.hideLoading();
  427. this.$emit('cropper', data);
  428. }
  429. },this);
  430. } else {
  431. uni.canvasToTempFilePath(
  432. {
  433. ...params,
  434. canvasId: 'tui-image-cropper',
  435. success: res => {
  436. data.url = res.tempFilePath;
  437. // #ifdef H5
  438. data.base64 = res.tempFilePath;
  439. // #endif
  440. this.loadding && uni.hideLoading();
  441. this.$emit('cropper', data);
  442. },
  443. fail(res) {
  444. console.log(res);
  445. }
  446. },
  447. this
  448. );
  449. }
  450. // #endif
  451. });
  452. };
  453. if (this.CROPPER_WIDTH != this.canvasWidth || this.CROPPER_HEIGHT != this.canvasHeight) {
  454. this.CROPPER_WIDTH = this.canvasWidth;
  455. this.CROPPER_HEIGHT = this.canvasHeight;
  456. this.$nextTick(() => {
  457. this.ctx.draw();
  458. setTimeout(() => {
  459. draw();
  460. }, 100);
  461. });
  462. } else {
  463. draw();
  464. }
  465. },
  466. change(e) {
  467. this.cutX = e.cutX || 0;
  468. this.cutY = e.cutY || 0;
  469. this.canvasWidth = e.canvasWidth || this.width;
  470. this.canvasHeight = e.canvasHeight || this.height;
  471. this.imgWidth = e.imgWidth || this.imgWidth;
  472. this.imgHeight = e.imgHeight || this.imgHeight;
  473. this.scale = e.scale || 1;
  474. this.angle = e.angle || 0;
  475. this.imgTop = e.imgTop || 0;
  476. this.imgLeft = e.imgLeft || 0;
  477. },
  478. imageReset() {
  479. this.scale = 1;
  480. this.angle = 0;
  481. let sys = this.sysInfo.windowHeight ? this.sysInfo : uni.getSystemInfoSync();
  482. this.imgTop = sys.windowHeight / 2;
  483. this.imgLeft = sys.windowWidth / 2;
  484. this.resetChange++;
  485. this.props = `4,${this.resetChange}`;
  486. //初始化旋转角度 0deg
  487. this.$emit('initAngle', {});
  488. },
  489. imageLoad(e) {
  490. this.imageReset();
  491. uni.hideLoading();
  492. this.$emit('imageLoad', {});
  493. },
  494. imgComputeSize(width, height) {
  495. //默认按图片最小边 = 对应裁剪框尺寸
  496. let imgWidth = width,
  497. imgHeight = height;
  498. if (imgWidth && imgHeight) {
  499. if (imgWidth / imgHeight > this.width / this.height) {
  500. imgHeight = this.height;
  501. imgWidth = (width / height) * imgHeight;
  502. } else {
  503. imgWidth = this.width;
  504. imgHeight = (height / width) * imgWidth;
  505. }
  506. } else {
  507. let sys = this.sysInfo.windowHeight ? this.sysInfo : uni.getSystemInfoSync();
  508. imgWidth = sys.windowWidth;
  509. imgHeight = 0;
  510. }
  511. this.imgWidth = imgWidth;
  512. this.imgHeight = imgHeight;
  513. this.sizeChange++;
  514. this.props = `2,${this.sizeChange}`;
  515. },
  516. moveStop() {
  517. clearTimeout(this.TIME_CUT_CENTER);
  518. this.TIME_CUT_CENTER = setTimeout(() => {
  519. if (!this.cutAnimation) {
  520. this.cutAnimation = true;
  521. }
  522. this.centerChange++;
  523. this.props = `5,${this.centerChange}`;
  524. }, 666);
  525. },
  526. moveDuring() {
  527. clearTimeout(this.TIME_CUT_CENTER);
  528. },
  529. showLoading() {
  530. uni.showLoading({
  531. title: '请稍候...',
  532. mask: true
  533. });
  534. },
  535. stop() {},
  536. back() {
  537. this.$emit('back')
  538. },
  539. angleChanged(val) {
  540. this.moveStop();
  541. if (this.limitMove && val % 90) {
  542. this.angle = Math.round(val / 90) * 90;
  543. }
  544. this.angleChange++;
  545. this.props = `3,${this.angleChange}`;
  546. },
  547. setAngle() {
  548. this.cutAnimation = true;
  549. this.angle = this.angle + 90;
  550. this.angleChanged(this.angle);
  551. }
  552. }
  553. };
  554. </script>
  555. <style scoped>
  556. .tui-container {
  557. width: 100vw;
  558. height: 100vh;
  559. background-color: rgba(0, 0, 0, 0.6);
  560. position: fixed;
  561. top: 0;
  562. left: 0;
  563. z-index: 1;
  564. }
  565. .tui-image-cropper {
  566. width: 100vw;
  567. height: 100vh;
  568. position: absolute;
  569. }
  570. .tui-content {
  571. width: 100vw;
  572. height: 100vh;
  573. position: absolute;
  574. z-index: 9;
  575. display: flex;
  576. flex-direction: column;
  577. pointer-events: none;
  578. }
  579. .tui-bg-transparent {
  580. background-color: rgba(0, 0, 0, 0.6);
  581. transition-duration: 0.3s;
  582. }
  583. .tui-content-top {
  584. pointer-events: none;
  585. }
  586. .tui-content-middle {
  587. width: 100%;
  588. height: 200px;
  589. display: flex;
  590. box-sizing: border-box;
  591. }
  592. .tui-cropper-box {
  593. position: relative;
  594. /* transition-duration: 0.2s; */
  595. border-style: solid;
  596. border-width: 1rpx;
  597. box-sizing: border-box;
  598. }
  599. .tui-flex-auto {
  600. flex: auto;
  601. }
  602. .tui-cropper-image {
  603. width: 100%;
  604. border-style: none;
  605. position: absolute;
  606. top: 0;
  607. left: 0;
  608. z-index: 2;
  609. -webkit-backface-visibility: hidden;
  610. backface-visibility: hidden;
  611. transform-origin: center;
  612. }
  613. .tui-cropper-canvas {
  614. position: fixed;
  615. z-index: 10;
  616. left: -2000px;
  617. top: -2000px;
  618. pointer-events: none;
  619. }
  620. .tui-edge {
  621. border-style: solid;
  622. pointer-events: auto;
  623. position: absolute;
  624. box-sizing: border-box;
  625. }
  626. .tui-top-left {
  627. border-bottom-width: 0 !important;
  628. border-right-width: 0 !important;
  629. }
  630. .tui-top-right {
  631. border-bottom-width: 0 !important;
  632. border-left-width: 0 !important;
  633. }
  634. .tui-bottom-left {
  635. border-top-width: 0 !important;
  636. border-right-width: 0 !important;
  637. }
  638. .tui-bottom-right {
  639. border-top-width: 0 !important;
  640. border-left-width: 0 !important;
  641. }
  642. .tui-cropper-tabbar {
  643. width: 100%;
  644. height: 120rpx;
  645. padding: 0 40rpx;
  646. box-sizing: border-box;
  647. position: fixed;
  648. left: 0;
  649. bottom: 0;
  650. z-index: 99;
  651. display: flex;
  652. align-items: center;
  653. justify-content: space-between;
  654. color: #ffffff;
  655. font-size: 32rpx;
  656. }
  657. .tui-cropper-tabbar::after {
  658. content: ' ';
  659. position: absolute;
  660. top: 0;
  661. right: 0;
  662. left: 0;
  663. border-top: 1rpx solid rgba(255, 255, 255, 0.2);
  664. -webkit-transform: scaleY(0.5) translateZ(0);
  665. transform: scaleY(0.5) translateZ(0);
  666. transform-origin: 0 100%;
  667. }
  668. .tui-op-btn {
  669. height: 80rpx;
  670. display: flex;
  671. align-items: center;
  672. }
  673. .tui-rotate-img {
  674. width: 44rpx;
  675. height: 44rpx;
  676. }
  677. </style>