Micro-channel front-end implementation applet custom share

background

Currently there are projects on hand a small program, we hope to share the message forwarding interface can customize, but micro-channel program provides only a small set of pictures url and title.

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {
        return {
          imageUrl:'',
          title:''
        };
    }
复制代码

achieve

Show what we want to forward something a little more: Avatar , username and Points of praise . Fortunately, this layout is not very complicated, so we thought about going to generate a picture through the canvas and then return url canvas picture generated.

Code is as follows (in fact, have to make some optimization on the display, go to your own specific debugging): first create a new canvas tag in the page

<canvas canvas-id="canvasid" style="width: 375px; height: 500px;" wx:if="{{canvasShow}}"></canvas>
复制代码
     let context = wx.createCanvasContext('canvasid')
     context.drawImage(back.path, 0, 60, backWidth, backHeight) //绘制下方背景图
     //绘制圆形头像,参考教程:https://www.jianshu.com/p/9a6ee2648d6f 第二种方法

      context.save();
      var d = 2 * 25;
      var cx = 0 + 25;
      var cy = 0 + 25;
      context.arc(cx, cy,25, 0, 2 * Math.PI);
      context.clip();
      context.drawImage(avatar.path, 0,0, d, d);
      context.restore();
      //绘制名字和点赞数
      context.setFontSize(14)
      context.fillText('userName', 70, 32)
      let zanLength = ('100' + '次赞').length
      context.fillText('100'+ '次赞', 375 - 14 * zanLength, 32)
      //执行draw进行渲染 并返回图片url
      context.draw(true, () => {
        //此方法应执行在draw的回调中
        wx.canvasToTempFilePath({
          x: 0,
          y: 0,
          width: 375,
          height: 400,
          destWidth: 375,
          destHeight: 400,
          canvasId: 'canvasid',
          success(res) {
        //设置onShareAppMessage所返回的数据格式
           let shareInfo = {
              title: 'customTitle',
              imageUrl
            }
           //隐藏画布
            that.setData({
              canvasShow: false
            })
          }
        })
      });
复制代码

however! Drawn in the canvas in the picture to be displayed is problematic (canvas pollution), non-homologous picture does not show up on the canvas in the real machine. Later we use wx.getImageInfo to acquire Image, through which address to show pictures (equivalent to turn a picture).

          wx.getImageInfo({
                src: imgUrl,
                success: function(res) {
                     /**拿到返回值res[0].path,再把该值作为canvas绘制图片的路径 
                        context.drawImage(res[0].path,x,x,x)**/
                    let drawImgUrl =  res[0].path
                }
            }); 
复制代码

emmmm .... article is very short, just provide some ideas to solve here, hoping to help to you ~

Reproduced in: https: //juejin.im/post/5d00abdd6fb9a07ebd48cecd

Guess you like

Origin blog.csdn.net/weixin_34290352/article/details/93168455