Image download of canvas drawing generation in wechat applet

Posted by ralba1998 on Mon, 09 Dec 2019 00:17:26 +0100

Functions to be implemented:

Click the circle of friends button to pop up the sharing picture:

Click Save share picture to save to mobile
Implementation code:
1. Sharing button click event

/**
   * share
   */
  weixinShare:function(){
    var that = this;
    console.log(111);
    share.canvasImg((res)=>{
      console.log(222);
      that.setData({
        imagePath: res.tempFilePath,
        bgShare:false,
        left:43
      });
    });
  }

2. Generate pictures

/**
   * Draw shared pictures
   */
  canvasImg(callback){
    //Applet QR code
    let promise1 = new Promise(function (resolve, reject) {
      /* Get the picture to draw on the canvas */
      wx.getImageInfo({
        src: '/images/qrcode.png',
        success: function (res) {
          console.log(res)
          resolve(res);
        }
      })
    });
    //background image
    let promise2 = new Promise(function (resolve, reject) {
      wx.getImageInfo({
        src: '/images/bg1.png',
        success: function (res) {
          console.log(res)
          resolve(res);
        }
      })
    });
    //User head
    let promise3 = new Promise(function (resolve, reject) {
      wx.getImageInfo({
        src: '/images/logo.png',
        success: function (res) {
          console.log(res)
          resolve(res);
        }
      })
    });
    Promise.all(
      [promise1, promise2, promise3]
    ).then(res => {
      const ctx = wx.createCanvasContext('shareWeixin')
      ctx.setFillStyle('#FFFFFF');
      ctx.fillRect(0,0,500,600);
      ctx.drawImage('../../../' + res[0].path, 220, 321, 100, 100)
      ctx.drawImage('../../../' + res[1].path, 0, 0, 331, 252)
      ctx.drawImage('../../../' + res[2].path, 10, 275, 30, 30)
        // Draw the text position, calculate the parameters by yourself, and read the document by yourself
      // ctx.setTextAlign('left ') / / location

      ctx.setFillStyle('#000000 ') / / color
      ctx.setFontSize(15);
      ctx.fillText('One Piece',54,300);
      ctx.setFontSize(22)           //  Font size
      ctx.fillText('Life reporter', 10, 341)//  Content will not wrap by itself, need to wrap manually
      ctx.fillText('Come and watch the campus news', 10, 377) //  content
      ctx.setFillStyle('#ccc') 
      ctx.setFontSize(15)
      ctx.fillText('Long press ID scan code to view details',10,410);
      /* Draw */
      ctx.stroke()
      ctx.draw(true,setTimeout(function(){
        wx.canvasToTempFilePath({
          x: 0,
          y: 0,
          width: 600,
          height: 800,
          destWidth: 600,
          destHeight: 800,
          canvasId: 'shareWeixin',
          success: function (res) {
            // wx.saveImageToPhotosAlbum({
            //   filePath: res.tempFilePath,
            // })
            callback && callback(res)
          },
          fail: function (res) {
            console.log(res)
          }
        })
      },500))
    })
  }

3. Save to phone

// Save to phone picture
  saveToPhone:function(){
    var that = this;
    // console.log(that.data.imagePath);
    // Save to local
    wx.downloadFile({
      url: that.data.imagePath,
      success: function (res) {
        tempFilePaths = res.tempFilePath
        wx.saveFile({
          tempFilePath: tempFilePaths,
          success(res) {
            savedFilePath = res.savedFilePath
            // console.log('save path ');
            // console.log(savedFilePath)
            // Save to phone
            wx.saveImageToPhotosAlbum({
              filePath: savedFilePath,
              success(res) {
                console.log(res)
                wx.showToast({
                  title: 'Success',
                  icon: 'success',
                  duration: 2000
                })
              },
              fail(res) {
                console.log('Failed to save to phone');
                console.log(res)
              }
            })
          }
        })        
      }, fail: function (res) {
        console.log('Save to local failed');
        console.log(res)
      }
    })
  }

5. Front end code

<!-- Sharing pictures -->
<view class='bg-shade' hidden="{{bgShare}}"></view> 
<canvas style="width: 600rpx; height: 800rpx;left:{{left}}px;" canvas-id="shareWeixin" class='share-bg'></canvas>
<view hidden='{{bgShare}}' class='preview'>
  <image src='{{imagePath}}' class='shareImg'></image> 
  <button type='primary' size='default' bindtap='saveToPhone'>Save sharing chart</button>
</view> 

Conclusion:

  • When drawing a picture, you need to delay certain events or it will fail to generate a blank picture of the same size
  • When downloading pictures, do not use temporary picture links directly. You can download the local links first and then save them
  • When drawing with canvas, you can't hide the canvas, otherwise it will report an error, so you can set the up and down distance between the left and right to let it locate out of the screen

Topics: Javascript QRCode