微信小程序引用we-cropper裁切图片

时间:2022-07-24
本文章向大家介绍微信小程序引用we-cropper裁切图片,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

文档地址 github下载源码直达链接 复制dist文件夹中的 .min.js.wxml文件到项目中

我引入的目录结构

page页面

<view>
    <view class='avatar'>
        <image mode='scaleToFill' src="{{avatar}}" bindtap='chooseimg'></image>
    </view>
    <view wx:if="{{showWeCropper}}">
        <import src='../../utils/weCropper/we-cropper.wxml' />
        <view class="cropperbg">
            <template is="we-cropper" data="{{...cropperOpt}}" />
            <view class="employ" bindtap="getCropperImage">使用</view>
        </view>
    </view>
</view>
.avatar {
    width: 200rpx;
    height: 200rpx;
    border-radius: 50%;
    overflow: hidden;
}

image {
    width: 100%;
    height: 100%;
}

.cropperbg {
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    background: #000;
}

.cropper {
    background: #000;
}

.employ {
    width: 360rpx;
    height: 80rpx;
    background: #16BA98;
    border-radius: 45rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    margin: 0 auto;
}
import WeCropper from '../../utils/weCropper/we-cropper.min.js'
const device = wx.getSystemInfoSync() // 获取设备信息
const width = device.windowWidth
const height = device.windowHeight - 100;
Page({
  data: {
    showWeCropper: false,
    cropperOpt: {
      id: 'cropper',
      width,
      height,
      scale: 2.5,
      zoom: 8,
      cut: {
        x: (width - 300) / 2,
        y: (height - 300) / 2,
        width: 300,
        height: 300
      }
    },
    avatar: 'https://sucai.suoluomei.cn/sucai_zs/images/20200516105950-2.png',
  },
  
  onLoad: function (options) {
    this.initWeCropper()
  },

  // 初始化weCropper插件图
  initWeCropper() {
    const {
      cropperOpt
    } = this.data
    this.cropper = new WeCropper(cropperOpt)
      .on('ready', (ctx) => {})
      .on('beforeImageLoad', (ctx) => {
        wx.showToast({
          title: '上传中',
          icon: 'loading',
          duration: 20000
        })
      })
      .on('imageLoad', (ctx) => {
        wx.hideToast()
      })
  },

  //选择图片
  chooseimg() {
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        this.setData({
          showWeCropper: true
        });
        this.cropper.pushOrign(res.tempFilePaths[0]);
      }
    })
  },

  touchStart(e) {
    this.cropper.touchStart(e)
  },
  touchMove(e) {
    this.cropper.touchMove(e)
  },
  touchEnd(e) {
    this.cropper.touchEnd(e)
  },

  // 获取图片链接
  getCropperImage() {
    this.cropper.getCropperImage((res) => {
      this.setData({
        showWeCropper: false,
        avatar: res,
      })
      console.log(res)
    })
  }
})