u-cropper.vue 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  1. <template>
  2. <view class="u-cropper">
  3. <view class="u-cropper__container"
  4. @touchstart.prevent="handleTouchStart"
  5. @touchmove.prevent="handleTouchMove"
  6. @touchend.prevent="handleTouchEnd">
  7. <!-- 遮罩层和裁剪框 -->
  8. <view class="u-cropper__mask">
  9. <!-- 裁剪框边框 -->
  10. <view class="u-cropper__cropbox" :class="[showGrid && 'u-cropper__cropbox_grid', `u-cropper__cropbox_${shape}`]" :style="[cropBoxStyle]">
  11. <view v-if="shape === 'square'" class="u-cropper__edge u-cropper__edge--1"></view>
  12. <view v-if="shape === 'square'" class="u-cropper__edge u-cropper__edge--2"></view>
  13. <view v-if="shape === 'square'" class="u-cropper__edge u-cropper__edge--3"></view>
  14. <view v-if="shape === 'square'" class="u-cropper__edge u-cropper__edge--4"></view>
  15. </view>
  16. </view>
  17. <!-- 图片层 -->
  18. <image
  19. v-if="viewData.imageLoaded && viewData.imageSrc"
  20. class="u-cropper__image"
  21. :src="viewData.imageSrc"
  22. :style="[imageStyle]"
  23. mode="aspectFit"
  24. @error="onImageError"
  25. />
  26. </view>
  27. <!-- 工具栏 -->
  28. <view class="u-cropper__tools">
  29. <view class="u-cropper__button__cancel" @click="close">
  30. <text>{{ cancelText }}</text>
  31. </view>
  32. <!-- #ifdef MP-WEIXIN -->
  33. <view class="cropper__button__choose">
  34. <button
  35. v-if="openType == 'chooseAvatar'"
  36. class="u-reset-button"
  37. hover-class="none"
  38. open-type="chooseAvatar"
  39. @click="chooseAvatar"
  40. @chooseavatar="chooseAvatar"
  41. >
  42. <u-icon name="photo" size="36" color="#fff"/>
  43. </button>
  44. <u-icon v-else name="photo" size="36" color="#fff" @click="chooseImage"/>
  45. </view>
  46. <!-- #endif -->
  47. <!-- #ifndef MP-WEIXIN -->
  48. <view class="cropper__button__choose" @click="chooseImage">
  49. <u-icon name="photo" size="36" color="#fff"/>
  50. </view>
  51. <!-- #endif -->
  52. <view class="cropper__button__rotate" @click="rotateImage">
  53. <u-icon name="rotate" size="36" color="#fff"/>
  54. </view>
  55. <view class="u-cropper__button__confirm" @click="confirmCrop(false)">
  56. <text>{{ confirmText }}</text>
  57. </view>
  58. </view>
  59. <!-- Canvas层 -->
  60. <canvas
  61. <!-- #ifdef MP-WEIXIN -->
  62. type="2d"
  63. <!-- #endif -->
  64. :canvas-id="canvasId"
  65. :id="canvasId"
  66. class="u-cropper__canvas" :style="[canvasStyle]"></canvas>
  67. </view>
  68. </template>
  69. <script>
  70. import props from './props.js';
  71. import mixin from '../../libs/mixin/mixin'
  72. import mpMixin from '../../libs/mixin/mpMixin';
  73. import ImageCropper from './cropper.js';
  74. /**
  75. * Cropper 图片裁剪组件
  76. * @description 封装的图片裁剪组件,支持图片选择、裁剪、旋转等功能,适用于头像上传、图片编辑等场景
  77. * @tutorial https://uview.d3u.cn/components/cropper.html
  78. *
  79. * @property {Boolean} autoChoose 每次显示时是否自动打开选择图片(默认 false )
  80. * @property {String | Number} rectWidth 裁剪框宽度,单位px(默认 200 )
  81. * @property {String | Number} rectHeight 裁剪框高度,单位px(默认 200 )
  82. * @property {String | Number} width 输出图片宽度,单位px(默认 200 )
  83. * @property {String | Number} height 输出图片高度,单位px(默认 200 )
  84. * @property {String} fileType 输出图片格式,支持jpg/png,建议使用jpg减小文件大小(默认 'jpg' )
  85. * @property {Boolean} showGrid 是否显示网格线(默认 true )
  86. * @property {String} shape 输入框形状,circle-圆形,square-方形 ( 默认 'square' )
  87. * @event {Function} change 选择图片时触发,返回原始图片路径
  88. * @event {Function} open 打开裁剪弹窗时触发
  89. * @event {Function} close 关闭裁剪弹窗时触发
  90. * @event {Function} confirm 确认裁剪时触发,返回裁剪后的图片临时路径
  91. * @example <u-cropper @confirm="onCropperConfirm"></u-cropper>
  92. */
  93. export default {
  94. name: "u-cropper",
  95. mixins: [mpMixin, mixin, props],
  96. data() {
  97. return {
  98. cropper: null,
  99. canvasId: 'cropper' + uni.$u.guid(),
  100. viewData: {
  101. imageLoaded: false,
  102. imageSrc: '',
  103. imageData: {},
  104. canvasWidth: 0,
  105. canvasHeight: 0,
  106. rectWidth: 0,
  107. rectHeight: 0
  108. }
  109. };
  110. },
  111. computed: {
  112. // 图片样式 - 从原始数据计算
  113. imageStyle() {
  114. const imageData = this.viewData.imageData;
  115. if (!this.viewData.imageLoaded || !imageData || !imageData.width) return {};
  116. let duration = '0s';
  117. let transform = `translate3d(${imageData.x}px, ${imageData.y}px,0)`;
  118. if (imageData.angle && imageData.angle !== 0) {
  119. duration = '0.3s';
  120. transform += ` rotate(${imageData.angle}deg)`;
  121. }
  122. return {
  123. width: uni.$u.addUnit(imageData.width),
  124. height: uni.$u.addUnit(imageData.height),
  125. transform: transform,
  126. transitionDuration: duration
  127. };
  128. },
  129. // 裁剪框样式 - 从原始数据计算
  130. cropBoxStyle() {
  131. if (!this.viewData.canvasWidth) return {};
  132. const rectX = (this.viewData.canvasWidth - this.viewData.rectWidth) / 2;
  133. const rectY = (this.viewData.canvasHeight - this.viewData.rectHeight) / 2;
  134. return {
  135. boxShadow: '0 0 0 '+ this.viewData.canvasWidth +'px rgba(0, 0, 0, 0.5)',
  136. left: uni.$u.addUnit(rectX),
  137. top: uni.$u.addUnit(rectY),
  138. width: uni.$u.addUnit(this.viewData.rectWidth),
  139. height: uni.$u.addUnit(this.viewData.rectHeight)
  140. };
  141. },
  142. canvasStyle() {
  143. return {
  144. width: uni.$u.addUnit(this.width),
  145. height: uni.$u.addUnit(this.height)
  146. }
  147. }
  148. },
  149. mounted() {
  150. this.$nextTick(async ()=>{
  151. await uni.$u.sleep(30)
  152. this.initCropper();
  153. })
  154. },
  155. watch: {
  156. },
  157. // #ifdef VUE3
  158. emits: ['change', 'open', 'close','confirm','error'],
  159. // #endif
  160. methods: {
  161. // 初始化裁剪器
  162. async initCropper() {
  163. const options = {
  164. canvasId: this.canvasId,
  165. width: uni.$u.getPx(this.width),
  166. height: uni.$u.getPx(this.height),
  167. rectWidth: uni.$u.getPx(this.rectWidth),
  168. rectHeight: uni.$u.getPx(this.rectHeight),
  169. watermark: this.watermark,
  170. fileType: this.fileType,
  171. quality: this.quality,
  172. onUpdate: (viewData) => {
  173. this.viewData = viewData;
  174. }
  175. };
  176. // #ifdef MP-WEIXIN
  177. options.type = '2d';
  178. // #endif
  179. this.cropper = new ImageCropper(this, options);
  180. this.$emit('open');
  181. if(this.autoChoose) {
  182. this.chooseImage();
  183. }
  184. },
  185. // 加载图片
  186. loadImage(src) {
  187. if (!this.cropper) return;
  188. this.cropper.setImage(src).catch(err => {
  189. this.$emit('error', uni.$u.$t('uCropper.loadImageError'));
  190. });
  191. },
  192. chooseAvatar(e) {
  193. const path = e.detail.avatarUrl;
  194. if (path) {
  195. this.$emit('change', path);
  196. this.loadImage(path);
  197. }
  198. },
  199. // 选择图片
  200. chooseImage() {
  201. uni.chooseImage({
  202. count: 1,
  203. sizeType: ['original', 'compressed'],
  204. sourceType: ['album', 'camera'],
  205. success: (res) => {
  206. const imagePath = res.tempFilePaths[0];
  207. this.$emit('change', imagePath);
  208. this.loadImage(imagePath);
  209. },
  210. fail: () => {
  211. this.$emit('error', uni.$u.$t('uCropper.chooseImageError'));
  212. }
  213. });
  214. },
  215. // 图片加载失败
  216. onImageError(e) {
  217. this.$emit('error', uni.$u.$t('uCropper.loadImageError'));
  218. },
  219. // 旋转图片
  220. rotateImage() {
  221. if (this.cropper) {
  222. this.cropper.rotate(90);
  223. }
  224. },
  225. // 重置图片
  226. resetImage() {
  227. if (this.cropper) {
  228. this.cropper.reset();
  229. }
  230. },
  231. // 确认裁剪
  232. async confirmCrop() {
  233. if (!this.cropper || !this.viewData.imageLoaded) {
  234. this.$emit('error', uni.$u.t('uCropper.chooseImage'));
  235. return;
  236. }
  237. uni.showLoading({
  238. title: uni.$u.$t('uCropper.cropping'),
  239. mask: true
  240. });
  241. this.cropper.getCropperImage().then((res)=>{
  242. this.$emit('confirm',res);
  243. this.close();
  244. }).catch(err => {
  245. this.$emit('error', uni.$u.$t('uCropper.cropError'));
  246. }).finally(()=>{
  247. uni.hideLoading();
  248. });
  249. },
  250. // 关闭裁剪器
  251. close() {
  252. if (this.cropper) {
  253. this.cropper.destroy();
  254. this.cropper = null;
  255. }
  256. this.viewData = {};
  257. this.$emit('close');
  258. },
  259. // 处理触摸开始 - 兼容各平台
  260. handleTouchStart(e) {
  261. if (!this.cropper) return;
  262. // 阻止默认行为和事件冒泡
  263. e.preventDefault && e.preventDefault();
  264. e.stopPropagation && e.stopPropagation();
  265. // 兼容不同平台的触摸事件
  266. let touch;
  267. // #ifdef H5
  268. touch = e.touches ? e.touches[0] : e;
  269. // #endif
  270. // #ifndef H5
  271. touch = e.touches && e.touches[0] ? e.touches[0] : e.changedTouches && e.changedTouches[0] ? e.changedTouches[0] : e;
  272. // #endif
  273. const event = {
  274. touches: [{
  275. clientX: touch.clientX || touch.x || touch.pageX,
  276. clientY: touch.clientY || touch.y || touch.pageY
  277. }]
  278. };
  279. this.cropper.touchStart(event);
  280. },
  281. // 处理触摸移动 - 兼容各平台
  282. handleTouchMove(e) {
  283. if (!this.cropper) return;
  284. // 阻止默认行为和事件冒泡
  285. e.preventDefault && e.preventDefault();
  286. e.stopPropagation && e.stopPropagation();
  287. // 兼容不同平台的触摸事件
  288. let touch;
  289. // #ifdef H5
  290. touch = e.touches ? e.touches[0] : e;
  291. // #endif
  292. // #ifndef H5
  293. touch = e.touches && e.touches[0] ? e.touches[0] : e.changedTouches && e.changedTouches[0] ? e.changedTouches[0] : e;
  294. // #endif
  295. const event = {
  296. touches: [{
  297. clientX: touch.clientX || touch.x || touch.pageX,
  298. clientY: touch.clientY || touch.y || touch.pageY
  299. }],
  300. preventdefault: () => ({})
  301. };
  302. this.cropper.touchMove(event);
  303. },
  304. // 处理触摸结束 - 兼容各平台
  305. handleTouchEnd(e) {
  306. if (!this.cropper) return;
  307. // 阻止默认行为和事件冒泡
  308. e.preventDefault && e.preventDefault();
  309. e.stopPropagation && e.stopPropagation();
  310. this.cropper.touchEnd(e);
  311. }
  312. },
  313. // #ifdef VUE2
  314. beforeDestroy() {
  315. if (this.cropper) {
  316. this.cropper.destroy();
  317. this.cropper = null;
  318. }
  319. }
  320. // #endif
  321. // #ifdef VUE3
  322. beforeUnmount() {
  323. if (this.cropper) {
  324. this.cropper.destroy();
  325. this.cropper = null;
  326. }
  327. }
  328. // #endif
  329. };
  330. </script>
  331. <style scoped lang="scss">
  332. .u-cropper {
  333. position: fixed;
  334. top: 0;
  335. left: 0;
  336. right: 0;
  337. bottom: 0;
  338. z-index: 999;
  339. background: #000;
  340. &__mask {
  341. position: absolute;
  342. top: 0;
  343. left: 0;
  344. right: 0;
  345. bottom: 0;
  346. z-index: 2;
  347. }
  348. &__cropbox {
  349. position: absolute;
  350. background: transparent;
  351. box-sizing: border-box;
  352. border: 1px solid rgba(255, 255, 255, .5);
  353. &_grid {
  354. &::before{
  355. content: '';
  356. position: absolute;
  357. top: 33.3333%;
  358. height: 33.3333%;
  359. left: 0;
  360. width: 100%;
  361. border: 1px dashed rgba(255, 255, 255, .5);
  362. }
  363. &::after{
  364. content: '';
  365. position: absolute;
  366. top: 0;
  367. left: 33.3333%;
  368. width: 33.3333%;
  369. height: 100%;
  370. border: 1px dashed rgba(255, 255, 255, .5);
  371. }
  372. }
  373. &_circle{
  374. border-radius: 100%;
  375. overflow: hidden;
  376. }
  377. &_square{
  378. }
  379. }
  380. &__edge {
  381. position: absolute;
  382. border:3px solid #ffffff;
  383. width: 15px;
  384. height: 15px;
  385. &--1 {
  386. top: -3px;
  387. left: -3px;
  388. border-right: 0;
  389. border-bottom: 0;
  390. }
  391. &--2 {
  392. top: -3px;
  393. right: -3px;
  394. border-left: 0;
  395. border-bottom: 0;
  396. }
  397. &--3 {
  398. bottom: -3px;
  399. left: -3px;
  400. border-right: 0;
  401. border-top: 0;
  402. }
  403. &--4 {
  404. bottom: -3px;
  405. right: -3px;
  406. border-left: 0;
  407. border-top: 0;
  408. }
  409. }
  410. &__image {
  411. position: absolute;
  412. left: 0;
  413. top: 0;
  414. z-index: 1;
  415. display: block;
  416. transform-origin: center center;
  417. }
  418. // &__grid {
  419. // position: absolute;
  420. // top: 0;
  421. // left: 0;
  422. // right: 0;
  423. // bottom: 0;
  424. // &-line {
  425. // position: absolute;
  426. // background: rgba(255, 255, 255, 0.3);
  427. // &--v {
  428. // top: 0;
  429. // bottom: 0;
  430. // width: 1px;
  431. // &1 {
  432. // left: 33.33%;
  433. // }
  434. // &2 {
  435. // left: 66.67%;
  436. // }
  437. // }
  438. // &--h {
  439. // left: 0;
  440. // right: 0;
  441. // height: 1px;
  442. // &1 {
  443. // top: 33.33%;
  444. // }
  445. // &2 {
  446. // top: 66.67%;
  447. // }
  448. // }
  449. // }
  450. // }
  451. &__tools {
  452. position: absolute;
  453. bottom: 0;
  454. left: 0;
  455. right: 0;
  456. z-index: 100;
  457. padding: 20px;
  458. display: flex;
  459. flex-direction: row;
  460. align-items: center;
  461. justify-content: space-between;
  462. }
  463. &__button{
  464. &__cancel{
  465. color:#fff;
  466. font-weight: 700;
  467. width: 70px;
  468. height: 40px;
  469. line-height: 40px;
  470. text-align: center;
  471. }
  472. &__confirm {
  473. color:#fff;
  474. font-weight: 700;
  475. width: 70px;
  476. height: 40px;
  477. line-height: 40px;
  478. background-color: $u-primary;
  479. border-radius: 4px;
  480. text-align: center;
  481. }
  482. }
  483. &__canvas {
  484. position: absolute;
  485. left: -9999px;
  486. top: -9999px;
  487. opacity: 0;
  488. }
  489. }
  490. </style>