小程序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);
    },
  })

最後生成保存的海報圖片爲下圖這樣,具體樣式自己再調整一下就可以了。
在這裏插入圖片描述

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