1. 程式人生 > >微信小程式圖片裁剪

微信小程式圖片裁剪

在wxml頁面新增

<!--start 使用者自動擷取正方形照片  -->
<template name="we-cropper">
    <canvas
            class="cropper  {{cutImage}}" 
            disable-scroll="true"
            bindtouchstart="touchStart"
            bindtouchmove="touchMove"
            bindtouchend="touchEnd"
            style="width:{{width}}px;height:{{height}}px;"
            canvas-id="{{id}}">
    </canvas>
</template>


<view class="cropper-wrapper {{cutImage}}">
    <template is="we-cropper"  data="{{...cropperOpt}}"/>
      <view class="cropper-buttons ">
          <view class="upload boxshaw cropperUpload" bindtap="chooseimage">重新選擇</view>
          <view  class="boxshaw getCropperImage" bindtap="getCropperImage">確定</view>
      </view>
</view>

<!--end 使用者自動擷取正方形照片  -->

對應的js裡新增

import WeCropper from '../../utils/we-cropper/we-cropper.js'
const device = wx.getSystemInfoSync()
const width = device.windowWidth
const height = device.windowHeight - 100;

Page({

  data: {    

cropperOpt: {

      id: 'cropper',
      width,
      height,
      scale: 2.5,
      zoom: 8,
      cut: {
        x: (width - 300) / 2,
        y: (height - 300) / 2,
        width: 300,
        height: 300
      }
    }

  },

onLoad: function () {
    this.getdata();
    const { cropperOpt } = this.data
    new WeCropper(cropperOpt)
      .on('ready', (ctx) => {
        console.log(`wecropper is ready for work!`)
      })
      .on('beforeImageLoad', (ctx) => {
        console.log(`before picture loaded, i can do something`)
        console.log(`current canvas context:`, ctx)
        wx.showToast({
          title: '上傳中',
          icon: 'loading',
          duration: 20000
        })
      })
      .on('imageLoad', (ctx) => {
        console.log(`picture loaded`)
        console.log(`current canvas context:`, ctx)
        wx.hideToast()
      })
      .on('beforeDraw', (ctx, instance) => {
        console.log(`before canvas draw,i can do something`)
        console.log(`current canvas context:`, ctx)
      })
      .updateCanvas();
  },
  touchStart(e) {
    this.wecropper.touchStart(e)
  },
  touchMove(e) {
    this.wecropper.touchMove(e)
  },
  touchEnd(e) {
    this.wecropper.touchEnd(e)

  },

 chooseimage: function () {

    var that = this;

    wx.chooseImage({
      sizeType: ['original', 'compressed'],
      sourceType: [type],
      success: function (res) {
        that.setData({
          cutImage: 'show',
          addtribeConShow: 'hide'
        });
        that.wecropper.pushOrign(res.tempFilePaths[0]); 
      }

    })

},

getCropperImage() {
    var that = this;
    that.wecropper.getCropperImage((src) => {

      if (src) {

        //此處新增使用者確定裁剪後執行的操作 src是擷取到的圖片路徑

    }

        }

}

效果如下圖: