小程序canvas 绘制海报 保存到本地

wxml文件:

<view class='poste_box' id='canvas-container' style="width:1500px">
 	 <canvas canvas-id="myCanvas" style="width:1500px;height:2096px;" />
</view>
<view class='wrapper_fuc'>
    <button style='background-color:#fff;' class='btn_item iconfont icon-guanyu' bindtap="saveShareImg"> 保存图片</button>
</view>

wxss文件:

.poste_box{
    position: fixed;
    top: -9999999px;
}

js文件:

Page({
    data: {
      cardInfo: {
        bgiMG: "https://profile.csdnimg.cn/3/0/D/1_rob_gao", //需要https图片路径
        qrCode: "https://profile.csdnimg.cn/3/0/D/1_rob_gao", //需要https图片路径
        avatar: 'https://profile.csdnimg.cn/3/0/D/1_rob_gao', // 机构头像
        name: '啦啦啦啦啦', //姓名
      }
    },
  
    onLoad: function () {
      this.getbgiMGInfo();
    },
  
    /**
     * 先下载头像图片
     */
    getbgiMGInfo: function () {
      wx.showLoading({
        title: '生成中...',
        mask: true,
      });
      var that = this;
      wx.downloadFile({
        url: that.data.cardInfo.bgiMG, //头像图片路径
        success: function (res) {
          wx.hideLoading();
          if (res.statusCode === 200) {
            var bgiMGSrc = res.tempFilePath; //下载成功返回结果
            that.getQrCode(bgiMGSrc); //继续下载二维码图片
          } else {
            wx.showToast({
              title: '头像下载失败!',
              icon: 'none',
              duration: 2000,
              success: function () {
                var bgiMGSrc = "";
                that.getQrCode(bgiMGSrc);
              }
            })
          }
        }
      })
    },
  
    /**
     * 下载二维码图片
     */
    getQrCode: function (bgiMGSrc) {
      wx.showLoading({
        title: '生成中...',
        mask: true,
      });
      var that = this;
      wx.downloadFile({
        url: that.data.cardInfo.qrCode, //二维码路径
        success: function (res) {
          wx.hideLoading();
          if (res.statusCode === 200) {
            var codeSrc = res.tempFilePath;
            that.getavatar(bgiMGSrc, codeSrc);
          } else {
            wx.showToast({
              title: '二维码下载失败!',
              icon: 'none',
              duration: 2000,
              success: function () {
                var codeSrc = "";
                that.getavatar(bgiMGSrc, codeSrc);
              }
            })
          }
        }
      })
    },

    /**
     * 下载机构头像
     */
    getavatar: function (bgiMGSrc, codeSrc) {
        wx.showLoading({
          title: '生成中...',
          mask: true,
        });
        var that = this;
        wx.downloadFile({
          url: that.data.cardInfo.avatar, //二维码路径
          success: function (res) {
            wx.hideLoading();
            if (res.statusCode === 200) {
              var avatar = res.tempFilePath;
              that.sharePosteCanvas(bgiMGSrc, codeSrc, avatar);
            } else {
              wx.showToast({
                title: '机构头像下载失败!',
                icon: 'none',
                duration: 2000,
                success: function () {
                  var avatar = "";
                  that.sharePosteCanvas(bgiMGSrc, codeSrc, avatar);
                }
              })
            }
          },
          fail: function(err){
          }
        })
      },

  
    /**
     * 开始用canvas绘制分享海报
     * @param bgiMGSrc 下载的头像图片路径
     * @param codeSrc   下载的二维码图片路径
     */
    sharePosteCanvas: function (bgiMGSrc, codeSrc, avatar) {
      wx.showLoading({
        title: '生成中...',
        mask: true,
      })
      var that = this;
      var cardInfo = that.data.cardInfo; //需要绘制的数据集合
      const ctx = wx.createCanvasContext('myCanvas'); //创建画布
      var width = "";
      wx.createSelectorQuery().select('#canvas-container').boundingClientRect(function (rect) {
        var height = rect.width;
        var right = rect.right;
        width = rect.width ;
        ctx.setFillStyle('#fff');
        ctx.fillRect(0, 0, width, width*1048/750);

        //头像为正方形
        if (bgiMGSrc) {
          ctx.drawImage(bgiMGSrc, 0, 0, width, width*920/750);
        }
  
        //姓名
        if (cardInfo.name) {
          ctx.setFontSize(60);
          ctx.setFillStyle('#010101');
          ctx.setTextAlign('left');
          ctx.fillText(cardInfo.name, 300, width*920/750 + 150);
        }

        //  绘制二维码
        if (codeSrc) {
            ctx.drawImage(codeSrc, width-200, width*920/750 + 40, 180, 180)
        }

        //  绘制机构头像
        if (avatar) {

            //绘制的头像宽度
            let avatarurl_width = 180
            //绘制的头像高度
            let avatarurl_heigth = 180
            //绘制的头像在画布上的位置
            let avatarurl_x = 80
            //绘制的头像在画布上的位置
            let avatarurl_y =   width*920/750 + 40
            
            // 绘制头像
            ctx.save()
            // 开始创建一个路径
            ctx.beginPath()
            // 画一个圆形裁剪区域
            ctx.arc(avatarurl_width / 2 + avatarurl_x, avatarurl_heigth / 2 + avatarurl_y, avatarurl_width / 2, 0, Math.PI * 2, false)
            // 裁剪
            ctx.clip()
            // 绘制图片
            ctx.drawImage(avatar, avatarurl_x, avatarurl_y, avatarurl_width, avatarurl_heigth)
            // 恢复之前保存的绘图上下文
            ctx.restore()

            // ctx.drawImage(avatar, left, height*0.8 + 40, 44, 44)
        }
  
      }).exec()
  
      setTimeout(function () {
        ctx.draw();
        wx.hideLoading();
      }, 1000)
  
    },
  
    //点击保存到相册
    saveShareImg: function () {
      var that = this;
      wx.showLoading({
        title: '正在保存',
        mask: true,
      })
      setTimeout(function () {
        wx.canvasToTempFilePath({
          canvasId: 'myCanvas',
          x: 0, //指定的画布区域的左上角横座标   
          y: 0, //指定的画布区域的左上角纵座标   
          width: 1500, //指定的画布区域的宽度
          height: 2096, //指定的画布区域的高度
          destWidth: 750, //输出的图片的宽度
          destHeight: 1048, //输出的图片的高度
          success: function (res) {
            wx.hideLoading();
            var tempFilePath = res.tempFilePath;
            wx.saveImageToPhotosAlbum({
              filePath: tempFilePath,
              success(res) {
                wx.showToast({
                    title: '保存成功!',
                    icon: 'none',
                    duration: 2000
                  })
              },
              fail: function (res) {
                wx.showToast({
                  title: res.errMsg,
                  icon: 'none',
                  duration: 2000
                })
              }
            })
          }
        });
      }, 1000);
    },
  })

最后生成保存的海报图片为下图这样,具体样式自己再调整一下就可以了。
在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章