1. 程式人生 > >微信小程式canvas合成圖片 分享

微信小程式canvas合成圖片 分享

先要獲取圖片的資訊  然後將需要合成的內容用canvas繪製出來,得到一個合成好的畫布,接下來用 wx.canvasToTempFilePath 把當前畫布指定區域的內容匯出生成指定大小的圖片,並返回檔案路徑。這個時候的路徑 是微信的臨時路徑,瀏覽器是訪問不了的,因此需要請求伺服器  用 wx.uploadFile 將本地資源上傳到開發者伺服器。

在頁面的wxml中加入canvas元件如下:

<view class="canvasBox">
  <canvas canvas-id="shareCanvas" style="width:375px;height:300px"></canvas>
</view>

在js中

picture: function () {  //生成圖片
      let that = this;
      let p1 = new Promise(function (resolve, reject) {
        wx.getImageInfo({
          src: 圖片路徑,
          success(res) {
            resolve(res);
          }
        })
      }).then(res => {
        const ctx = wx.createCanvasContext('shareCanvas');
        ctx.drawImage(res.path, 0, 0, 375, 300);    //繪製背景圖
        //ctx.setTextAlign('center')    // 文字居中
        ctx.setFillStyle('#000000')  // 文字顏色:黑色
        ctx.setFontSize(20)         // 文字字號:22px
        ctx.fillText("文字內容", 20, 70) //開始繪製文字的 x/y 座標位置(相對於畫布) 
        ctx.stroke();//stroke() 方法會實際地繪製出通過 moveTo() 和 lineTo() 方法定義的路徑。預設顏色是黑色
        ctx.draw(false, that.drawPicture());//draw()的回撥函式 
        console.log(res.path);
      })
    },
    drawPicture: function () { //生成圖片
       var that = this;
      setTimeout(function(){
        wx.canvasToTempFilePath({ //把當前畫布指定區域的內容匯出生成指定大小的圖片,並返回檔案路徑
          x: 0,
          y: 0,
          width: 375,
          height: 300,
          destWidth: 375,  //輸出的圖片的寬度
          destHeight: 300,
          canvasId: 'shareCanvas',
          success: function (res) {
            console.log(res);
            that.draw_uploadFile(res);
          },
        })
      },300)
    },
    draw_uploadFile: function (r) { //wx.uploadFile 將本地資源上傳到開發者伺服器
      let that = this;
      wx.uploadFile({
        url: 圖片上傳介面, //線上介面
        filePath: r.tempFilePath,
        name: 'imgFile',
        success: function (res) {
          console.log(res);
          if(res.statusCode==200){
            res.data = JSON.parse(res.data);
            let imgsrc = res.data.data.src;
            that.setData({
              imgPath: imgsrc
            });
          }else{
            console.log('失敗')
          }
        },
      })
    },

注意:若是將此方法攜程自定義元件,則 wx.createCanvasContext 和 wx.canvasToTempFilePath 都需要多傳一個this,

因在自定義元件下,當前元件例項的this,用以操作元件內 <canvas/> 元件。

至於分享的話 ,拿到伺服器返回的圖片路徑之後 就可以用來寫分享的圖片路徑了