原生小程序使用we-cropper实现照片裁剪


      <import src="../we-cropper/we-cropper.wxml" />  <-- 引入 -->
        
      <template is="we-cropper" data="{{...cropperOpt}}" />
      <view class="cropperbg">
        <template is="we-cropper" data="{{...cropperOpt}}" />
        <view class="flex-wrap rowcenter mgt-15">
          <view class="operation_icon">
            <image src="/package/image/icon_cancel.png" bindtap="cancel_sel" />
            <image src="/package/image/icon_camera.png" bindtap="getCropperImage" />
          </view>

          <!-- <van-button
            type="info"
            bindtap="chooseimg"
            size="large"
            custom-style="width:90vw;border-radius:20rpx;height:80rpx"
          >选择图片
          </van-button>

          <van-button
            type="info"
            bindtap="getCropperImage"
            size="large"
            custom-style="width:90vw;border-radius:20rpx;height:80rpx"
          >保存
          </van-button> -->
        </view>
      </view>

import WeCropper from '../we-cropper/we-cropper'
const device = wx.getSystemInfoSync() // 获取设备信息
const width = device.windowWidth // 示例为一个与屏幕等宽的正方形裁剪框
const height = width
onLoad(option) {
  const { cropperOpt } = this.data
  this.cropper = new WeCropper(cropperOpt)
    .on('ready', (ctx) => {
    console.log(`wecropper is ready for work!`)
  })
    .on('beforeImageLoad', (ctx) => {
    wx.showToast({
      title: '上传中',
      icon: 'loading',
      duration: 20000,
    })
  })
    .on('imageLoad', (ctx) => {
    wx.hideToast()
  })
},
  
touchStart(e) {
  this.cropper.touchStart(e)
},
touchMove(e) {
  this.cropper.touchMove(e)
},
touchEnd(e) {
  this.cropper.touchEnd(e)
},
// 选择
selImg() {
  let that = this
  wx.chooseImage({
    count: 1,
    sizeType: ['original', 'compressed'],
    sourceType: ['album', 'camera'],
    success(res) {
      const tempFilePaths = res.tempFilePaths[0]
      that.cropper.pushOrign(tempFilePaths)
    },
  })
},
data:{
    cropperOpt: {
      id: 'cropper', // 用于手势操作的canvas组件标识符
      targetId: 'targetCropper', // 用于用于生成截图的canvas组件标识符
      pixelRatio: device.pixelRatio, // 传入设备像素比
      width, // 画布宽度
      height, // 画布高度
      scale: 2.5, // 最大缩放倍数
      zoom: 8, // 缩放系数
      cut: {
        x: (width - 200) / 2, // 裁剪框x轴起点
        y: (width - 200) / 2, // 裁剪框y轴期起点
        width: 200, // 裁剪框宽度
        height: 200, // 裁剪框高度
      },
    },
  }

官方文档
https://we-plugin.github.io/we-cropper/#/

posted @ 2023-02-17 09:03  小万子呀  阅读(486)  评论(0编辑  收藏  举报