微信小程式之裁剪圖片成圓形

碼農界段子手發表於2018-10-11

前言

最近在開發小程式,產品經理提了一個需求,要求微信小程式換頭像,使用者剪裁圖片必須是圓形,也在github上看了一些例子,一般剪裁圖片用的都是方形,所以自己打算寫一個小元件,可以把圖片剪裁成圓形,主要思路就是使用canvas繪圖,把剪裁的圖片繪製成圓形,另外剪裁圖片的視窗還可以移動放大縮小,這個功能就用了微信元件movable-view,好了,該說的也說完了,下面我們們開始擼程式碼。

movable-view元件

可移動的檢視容器,在頁面中可以拖拽滑動
會有好多個屬性,在這裡不一一介紹,只說我們能用到的就可以。
我們用到的屬性主要有:

  1. direction:movable-view的移動方向,屬性值有all、vertical、horizontal、none
  2. scale:是否支援雙指縮放,預設縮放手勢生效區域是在movable-view內
  3. scale-min 定義縮放倍數最小值
  4. scale-max 定義縮放倍數最大值
  5. bindchange 拖動過程中觸發的事件,event.detail = {x: x, y: y, source: source},其中source表示產生移動的原因,值可為touch(拖動)、touch-out-of-bounds(超出移動範圍)、out-of-bounds(超出移動範圍後的回彈)、friction(慣性)和空字串(setData)
  6. bindscale 縮放過程中觸發的事件,event.detail = {x: x, y: y, scale: scale},其中x和y欄位在2.1.0之後開始支援返回
    主要用到的就是這幾個值
    另外使用movable-view的時候必須在外邊加一個movable-area的父元素,不然的話沒有移動區域。
    movable-view 的可移動區域,屬性只有:
    scale-area 當裡面的movable-view設定為支援雙指縮放時,設定此值可將縮放手勢生效區域修改為整個movable-area,是個boolean值,預設false
    擷取區域的移動已經說完了,詳情請看傳送門

canvas繪圖

畫布。該元件是原生元件可以繪製影像,分享朋友圈生成海報就經常用到這個屬性,就簡單的說下:
在wxml中必須要有canvas這個標籤,才可以繪製影像,而且要有canvas-id屬性,代表canvas 元件的唯一識別符號,
還有許多API我就不一一介紹了,底下用的API程式碼當中都會用註釋。詳情請看微信小程式畫布API傳送門

程式碼實現

  1. 首先是選擇圖片
    wxml就是初始化一個按鈕點選的時候選擇圖片,而且需要引入我們封裝的擷取圖片元件,並把圖片作為引數傳進去,封裝元件方法請看我另一篇文章元件封裝

index.wxml
Tip: 必須把canvas放到引入剪裁元件的wxml中,否則繪製不成功,因為canvas是原生元件脫離在 WebView 渲染流程外。

<view class="container">
  <button wx:if="{{!imgSrc}}" bindtap="getImgurl"> 選擇圖片 </button>
  <view class="clip-box" wx:if="{{imgSrc}}">
      <ClipImg imgSrc="{{imgSrc}}"></ClipImg>
  </view>
</view>
<canvas canvas-id="myCanvas" style="position:absolute; width:100%;height:100%;border: 1px solid red;left: -9999px; top: -9999px;"></canvas>

 

index.json引入擷取圖片的元件

{
    "component": true,
    "usingComponents": {
        "ClipImg": "../../component/clipImg/clipImg"
    }
}

 

index.js上傳圖片顯示

const app = getApp()

Page({
  data: {
    imgSrc: ``
  },
  //選擇圖片
  getImgurl: function () {
    wx.chooseImage({
      count: 1, // 預設9
      sizeType: [`original`, `compressed`], // 可以指定是原圖還是壓縮圖,預設二者都有
      sourceType: [`album`, `camera`], // 可以指定來源是相簿還是相機,預設二者都有
      success:  (res) => {
        // 返回選定照片的本地檔案路徑列表,tempFilePath可以作為img標籤的src屬性顯示圖片
        const tempFilePaths = res.tempFilePaths;
        //啟動上傳等待中...  
        wx.showToast({  
          title: `正在上傳...`,  
          icon: `loading`,  
          mask: true,  
          duration: 1000 
        }) 
        this.setData({
          imgSrc: res.tempFilePaths
        })
      }
    })
  },
  onLoad: function () {
  }
})

 

接下來就是剪裁圖片元件的封裝
首先是頁面佈局,也就是clipImg.wxml

<view class="clip">
    <image class="head-img" style="width:{{cropperW}}rpx;height:{{cropperH}}rpx" src="{{imageUrl}}"></image>
    <movable-area scale-area style="width:{{cropperW}}rpx;height:{{cropperH}}rpx">
        <movable-view bindchange="move" bindscale="scale" direction="all" scale scale-min="0.5" scale-max="1.8">
        </movable-view>
    </movable-area>
    <view class="btn">
        <text bindtap="cancel">取消</text>
        <text bindtap="getImageInfo">儲存</text>
    </view>
</view>

 

大概就是這個樣子
圖片描述
上邊的圓就是擷取就是擷取框。
然後就是clipImg.js檔案主要就是對圖片擷取的一些操作

Component({
  /**
   * 元件的屬性列表
   */
  properties: {
    imgSrc: {
      type: `String`,
      value: ``
    }
  },

  /**
   * 元件的初始資料
   * imageUrl string 初始化圖片
   * cropperW string 縮小圖寬度
   * cropperH  string 縮小圖高度,
   * img_ratio string  圖片比例,
   * IMG_W string 原圖高度,
   * IMG_H string 原圖高度,
   * left string 圖片距離左邊距離,
   * top string 圖片距離上邊距離,
   * clipW number 預設擷取框
   */
  data: {
    imageUrl: ``,
    cropperW: ``,
    cropperH: ``,
    img_ratio: ``,
    IMG_W: ``,
    IMG_H: ``,
    left: ``,
    top: ``,
    clipW: 200
  },

  /**
   * 元件的方法列表
   */
  methods: {
    //點選取消
    cancel: function () {
      var myEventDetail = {} // detail物件,提供給事件監聽函式
      var myEventOption = {} // 觸發事件的選項
      this.triggerEvent(`myevent`, myEventDetail, myEventOption)
    },
    //拖拽事件
    move: function ({ detail }) {
      this.setData({
        left: detail.x * 2,
        top: detail.y * 2
      })
    },
    //縮放事件
    scale: function ({ detail }) {
      console.log(detail.scale)
      this.setData({
        clipW: 200 * detail.scale
      })
    },
    //生成圖片
    getImageInfo: function () {
      wx.showLoading({
        title: `圖片生成中...`,
      })
      const img_ratio = this.data.img_ratio;
      //要擷取canvas的寬
      const canvasW = (this.data.clipW / this.data.cropperW) * this.data.IMG_W
      //要擷取canvas的高
      const canvasH = (this.data.clipW / this.data.cropperH) * this.data.IMG_H
      //要擷取canvas到左邊距離
      const canvasL = (this.data.left / this.data.cropperW) * this.data.IMG_W
      //要擷取canvas到上邊距離
      const canvasT = (this.data.top / this.data.cropperH) * this.data.IMG_H
      // 將圖片寫入畫布
      const ctx = wx.createCanvasContext(`myCanvas`);
      //繪製影像到畫布
      ctx.save(); // 先儲存狀態 已便於畫完圓再用        
      ctx.beginPath(); //開始繪製  
      ctx.clearRect(0, 0, 1000, 1000)
      //先畫個圓      
      ctx.arc(this.data.clipW / 2, this.data.clipW / 2, this.data.clipW / 2, 0, 2 * Math.PI, false)
      ctx.clip();//畫了圓 再剪下  原始畫布中剪下任意形狀和尺寸。一旦剪下了某個區域,則所有之後的繪圖都會被限制在被剪下的區域內    
      ctx.drawImage(this.data.imageUrl, canvasL, canvasT, canvasW, canvasH, 0, 0, this.data.clipW, this.data.clipW); // 推進去圖片        
      ctx.restore(); //恢復之前儲存的繪圖上下文 恢復之前儲存的繪圖上下午即狀態 可以繼續繪製
      ctx.draw(true, () => {
        // 獲取畫布要裁剪的位置和寬度   
        wx.canvasToTempFilePath({
          x: 0,
          y: 0,
          width: this.data.clipW,
          height: this.data.clipW,
          destWidth: this.data.clipW,
          destHeight: this.data.clipW,
          quality: 0.5,
          canvasId: `myCanvas`,
          success: (res) => {
            wx.hideLoading()
            /**
             * 擷取成功後可以上傳的服務端直接呼叫
             * wx.uploadFile();
             */
            //成功獲得地址的地方
            wx.previewImage({
              current: ``, // 當前顯示圖片的http連結
              urls: [res.tempFilePath] // 需要預覽的圖片http連結列表
            })
          }
        })
      })
    }
  },
  ready: function () {
    this.setData({
      imageUrl: this.data.imgSrc[0]
    })
    //獲取圖片寬高
    wx.getImageInfo({
      src: this.data.imageUrl,
      success: (res) => {
        console.log(`圖片資訊`, res);
        //圖片實際款高
        const width = res.width;
        const height = res.height;
        //圖片寬高比例
        const img_ratio = width / height
        this.setData({
          img_ratio,
          IMG_W: width,
          IMG_H: height,
        })
        if (img_ratio >= 1) {
          //寬比較大,橫著顯示
          this.setData({
            cropperW: 750,
            cropperH: 750 / img_ratio,
          })
        } else {
          //豎著顯示
          this.setData({
            cropperW: 750 * img_ratio,
            cropperH: 750
          })
        }
      } 
    })
  }
})

 

到現在為止一個擷取圖片就完成了,可能會有些問題,比如擷取的圖片的框沒有居中,自己可以再次封裝這個元件,因為現在已經適合我們公司自己專案了。我們來預覽下。另外這個元件支援雙指放大擷取框來擷取圖片,不過微信開發者工具不能展示,自己可以把程式碼下載下來,在自己手機上掃碼檢視效果。

圖片描述
另外我把專案放到了github上邊,希望小哥哥小姐姐們多多點贊,多多支援,有什麼疑問可以在github上問我,謝謝。點讚的小哥哥小姐姐最可愛,哈哈哈。。。
專案地址連結描述

相關文章