天天看點

小程式頭像裁剪

1、建立一個頁面,放置畫布等,對裁剪圖檔進行操作

小程式頭像裁剪

1️⃣avatarCut.wxml:

<import src='../../components/dist/we-cropper'/>
<view class="cropper-wrapper">
  <template is="we-cropper" data="{{...cropperOpt}}"/>
  <view class="cropper-buttons">
    <canvas canvas-id='attendCanvasId' class='myCanvas' style="width:100px;height:100px;"></canvas>
    <view class="upload" bindtap="uploadTap">重新選擇</view>
    <view class="getCropperImage" bindtap="getCropperImage">确定</view>
  </view>
</view>
           

2️⃣avatarCut.js:

// pages/avatarCut/avatarCut.js
const app = getApp()
//引入的元件
import WeCropper from '../../components/dist/we-cropper'

const device = wx.getSystemInfoSync()
const width = device.windowWidth
const height = device.windowHeight - 150
const token = wx.getStorageSync('token')

Page({
  data: {
    cropperOpt: {
      id: 'cropper',
      width,
      height,
      scale: 2.5,
      zoom: 8,
      cut: {
        x: (width - 200) / 2,
        y: (height - 200) / 2,
        width: 200,
        height: 200
      }
    },
    avatar: "",
    canvasImgUrl: '',
    imageSize: ''

  },
  touchStart(e) {
    this.wecropper.touchStart(e)
  },
  touchMove(e) {
    this.wecropper.touchMove(e)
  },
  touchEnd(e) {
    this.wecropper.touchEnd(e)
  },
  //這個是儲存上傳裁剪後的圖檔的方法
  getCropperImage() {
    var that = this
   
    this.wecropper.getCropperImage((avatar) => {
      if (avatar) {
        that.getCanvasImg(0, 0, avatar);    //進行壓縮
        // that.uploadImage(avatar, (res) => { })
      } else {
        console.log('擷取圖檔失敗,請稍後重試')
      }
    })
  },
  //重新選擇頭像
  uploadTap() {
    const self = this

    wx.chooseMedia({
      count: 1, // 預設9
      sizeType: ['original', 'compressed'], // 可以指定是原圖還是壓縮圖,預設二者都有
      sourceType: ['album', 'camera'], // 可以指定來源是相冊還是相機,預設二者都有
      success: function (res) {
        const src = res.tempFilePaths[0]
        // 擷取裁剪圖檔資源後,給data添加src屬性及其值
        self.wecropper.pushOrign(src)
      }
    })
  },
  //壓縮并擷取圖檔,這裡用了遞歸的方法來解決canvas的draw方法延時的問題
  getCanvasImg: function (index, failNum, tempFilePaths) {
    var that = this;
    console.log(111)
    wx.getImageInfo({
      src: tempFilePaths, //圖檔的路徑,可以是相對路徑,臨時檔案路徑,存儲檔案路徑,網絡圖檔路徑,  
      success: res => {
        console.log(res)
          const ctx = wx.createCanvasContext('attendCanvasId');
          setTimeout(() => {
            ctx.drawImage(tempFilePaths, 0, 0, 100, 100);
            ctx.draw(true, function () {
              wx.canvasToTempFilePath({
                canvasId: 'attendCanvasId',
                success: function success(res) {
                  console.log(res)
                  that.uploadImage(res.tempFilePath,(res)=> { } );
                  
                }, fail: function (e) {
                  failNum += 1;//失敗數量,可以用來提示使用者
                  that.getCanvasImg(inedx, failNum, tempFilePaths);
                }
              });
            });
          }, 1000);
      },
      fail: () => { },
      complete: () => { }
    });
  },

  onLoad(option) {
      console.log(option);
    let that = this;
    const { cropperOpt } = this.data;
    var tempFilePaths = option.src;
    // that.setData({
    //   // tempFilePath可以作為img标簽的src屬性顯示圖檔
    //   avatar: option.src,
    // })
    if (option.src) {
      cropperOpt.src = option.src
      new WeCropper(cropperOpt)
        .on('ready', (ctx) => {
        })
        .on('beforeImageLoad', (ctx) => {
          // wx.showToast({
          //   title: '上傳中',
          //   icon: 'loading',
          //   duration: 2000
          // })
        })
        .on('imageLoad', (ctx) => {
          // wx.hideToast()
        })
        .on('beforeDraw', (ctx, instance) => {
        })
        .updateCanvas()
    }
  },

uploadImage (filePath, cb) {   //個人封裝的簡單的上傳單張圖檔上傳的方法
    wx.uploadFile({
      url: app.baseURL + '/User/uploadSinglePicture',
      filePath: filePath,
      name: 'file',
      header: {
        "Content-Type": "multipart/form-data"
      },
      formData: {
        token: app.globalData.token,
        file: filePath,
        type: 1
      },
      success: (res) => {
        console.log(res)
        let data = JSON.parse(res.data); //由于拿到的資料未解析,這裡先解析json
        if (data.code == 1){
          console.log(222)
          cb(res);
          wx.request({
            url: app.baseURL + '/user/profile',
            data: {
              token: wx.getStorageSync('token'),
              avatar: data.data,
              type: 1
            },
            success(res) {
              console.log(res)
              if (res.data.code == 1) {
                wx.showToast({
                  title: res.data.msg,
                })
              }
              //跳轉到"我的"頁面
              wx.switchTab({
                url: "/pages/my/index",//這個地方看個人需求了
              });
            }
          })
        }
      },
      fail: (res) => {
        wx.showToast({
          title: '上傳失敗',
        })
      },
    })
  }
})
           

2、首頁面從相冊或者拍照選擇圖檔

//點選上傳頭像方法
    showAction() {
        wx.showActionSheet({
            itemList: ['從相冊中選擇', '拍照'],
            success: (res) => {
                if (!res.cancel) {
                    console.log(res)
                    if (res.tapIndex == 0) {
                        this.chooseWxImage(['album'])
                    } else if (res.tapIndex == 1) {
                        this.chooseWxImage(['camera'])
                    }
                }
            }
        })
    },
// 跳轉畫布并傳參
    chooseWxImage(type) {
        wx.chooseMedia({
            count: 1,
            sizeType: ['original', 'compressed'],
            sourceType: type,
            success: (res) => {
                console.log(res);
                // that.setData({
                //   // tempFilePath可以作為img标簽的src屬性顯示圖檔
                //   avatar: res.tempFiles[0].tempFilePath,
                // })
                var tempFilePaths = res.tempFiles[0].tempFilePath;
                wx.navigateTo({
                    url: "/pages/avatarCut/avatarCut?src=" + tempFilePaths
                });
            }
        })
    },
           

we-cropper插件,一款靈活小巧的canvas圖檔裁剪器

https://gitcode.net/mirrors/we-plugin/we-cropper?utm_source=csdn_github_accelerator

下載下傳dist檔案夾放入components公共元件中

這隻是基礎的功能樣式,需要什麼效果自行修改