小程序生成海报并保存

wxml

<!-- 生成海报二维码并保存到相册 -->
<view class='cont' id='canvas-container'>
    <canvas canvas-id="myCanvas" style="width:100%;height:100%;" bindlongtap='saveShareImg' />
  </view>

wxss

page {
  background-color: #edeef2;
}
 
.cont {
  width: 80%;
  margin: auto;
  text-align: center;
  height: 1000rpx;
  margin-top: 50rpx;
  background:#ff8427;
  box-shadow:0rpx 0rpx  10rpx 5rpx rgb(100, 80, 204);
}
 
.savePoste {
  background-color: #ff8427;
  width: 90%;
  margin-left: auto;
  margin-right: auto;
  margin-top: 30rpx;
  color: #fff;
}
 
.saveTitle {
  font-size: 25rpx;
  color: #666;
  width: 90%;
  margin-left: auto;
  margin-right: auto;
  margin-top: 20rpx;
  text-align: center;
}

js

// pages/haibao/haibao.js
//获取应用实例
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    name:'大肉丸子',   //生成海报的名字
    cardBase: {
      //需要https图片路径,下载到本地然后去绘制
      cardbg: "../../images/personal/invitation.png",
      // 二维码
      codeImg: "../../images/personal/QR.png",
      avatar:"../../images/personal/avatar.png"
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var cardBase=that.data.cardBase;
    that.getCanvas(cardBase.cardbg, cardBase.codeImg,cardBase.avatar);

  },
/**
   * 先下载海报背景
   */
  getAvaterInfo: function() {
    wx.showLoading({
      title: '生成中...',
      mask: true,
    });
    var that = this;
    wx.downloadFile({
      url: that.data.cardBase.cardbg, 
      success: function(res) {
        wx.hideLoading();
        if (res.statusCode === 200) {
          //download下载成功返回结果res.tempFilePath
          var cardbg = res.tempFilePath; 
          that.getQrCode(cardbg); 
        } else {
          wx.showToast({
            title: '亲,海报下载失败!',
            icon: 'none',
            duration: 2000,
            success: function() {
              var cardbg = "";
              that.getQrCode(cardbg);
            }
          })
        }
      }
    })
  },
 
  /**
   * 下载二维码图片
   */
  getQrCode: function (cardbg) {
    wx.showLoading({
      title: '生成中...',
      mask: true,
    });
    var that = this;
    wx.downloadFile({
      url: that.data.cardInfo.codeImg,
      success: function(res) {
        wx.hideLoading();
        if (res.statusCode === 200) {
          var codeImg = res.tempFilePath;
          that.getCanvas(cardbg, codeImg);
        } else {
          wx.showToast({
            title: '二维码下载失败!',
            icon: 'none',
            duration: 2000,
            success: function() {
              var codeImg = "";
              that.getCanvas(cardbg, codeImg);
            }
          })
        }
      }
    })
    wx.downloadFile({
      url: that.data.cardInfo.avatar,
      success: function(res) {
        wx.hideLoading();
        if (res.statusCode === 200) {
          var avatar = res.tempFilePath;
          that.getCanvas(cardbg, avatar);
        } else {
          wx.showToast({
            title: '头像下载失败!',
            icon: 'none',
            duration: 2000,
            success: function() {
              var avatar = "";
              that.getCanvas(cardbg, avatar);
            }
          })
        }
      }
    })
  },
 
  /**
   * 开始用canvas绘制分享海报
   * @param cardbg 下载的海报背景图路径
   * @param codeImg   下载的二维码图片路径
   * @param avatar    下载的头像的图片
   */
  getCanvas: function (cardbg, codeImg,avatar) {
    wx.showLoading({
      title: '正在生成中...',
      mask: true,
    })
    var that = this;
    var cardBase = that.data.cardBase; //需要绘制的数据集合
    const ctx = wx.createCanvasContext('myCanvas'); //创建画布
    var width = "";
    wx.createSelectorQuery().select('#canvas-container').boundingClientRect(function(rect) {
      var height = rect.height;
      var right = rect.right;
      width = rect.width * 0.8;
      var left = rect.left + 5;
      ctx.setFillStyle('#fff');
      ctx.fillRect(0, 0, rect.width, height);
      // 这里处理自适应
      let rpx = 1;
      wx.getSystemInfo({
        success(res) {
          rpx = res.windowWidth / 375;
        },
      })
 
      //背景图
      if (cardbg) {
        ctx.drawImage(cardbg, 20*rpx,20*rpx, 260*rpx,460*rpx);
      }
    // 标题
      ctx.setFontSize(14);
      ctx.setFillStyle('#000');
      ctx.setTextAlign('left');
      ctx.fillText(that.data.name, 80 * rpx, 70 * rpx, 100 * rpx, 100 * rpx); //姓名
      //  绘制二维码
      if (codeImg) {
        ctx.drawImage(codeImg, 185 * rpx, 362 * rpx, 55 * rpx, 55 * rpx)
      }
      if(avatar){
        ctx.drawImage(avatar, 40 * rpx, 50 * rpx, 33 * rpx, 33 * rpx)
      }
 
    }).exec()
 
    setTimeout(function() {
      ctx.draw();
      wx.hideLoading();
    }, 1000)
 
  },
 
 
  //点击保存到相册
  saveShareImg: function() {
    var that = this;
    wx.showLoading({
      title: '正在保存',
      mask: true,
    })
    setTimeout(function() {
      wx.canvasToTempFilePath({
        canvasId: 'myCanvas',
        success: function(res) {
          console.info("res", res);
          wx.hideLoading();
          var tempFilePath = res.tempFilePath;
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success(res) {
              console.info(res);
              wx.showModal({
                content: '图片已保存到相册,赶紧晒一下吧~',
                showCancel: false,
                confirmText: '好的',
                confirmColor: '#333',
                success: function(res) {
                  if (res.confirm) {}
                },
                fail: function(res) {}
              })
            },
            fail: function(res) {
              console.log(res)
              if (res.errMsg === "saveImageToPhotosAlbum:fail:auth denied") {
                console.log("打开设置窗口");
                wx.openSetting({
                  success(settingdata) {
                    console.log(settingdata)
                    if (settingdata.authSetting["scope.writePhotosAlbum"]) {
                      console.log("获取权限成功,再次点击图片保存到相册")
                    } else {
                      console.log("获取权限失败")
                    }
                  }
                })
              }
            }
          })
        }
      });
    }, 1000);
  },

})

 注意:canvas不能使用网络地址

解决方法:用wx.downloadFile()方法下载图片,然后就可以使用显示在海报上啦。

posted @ 2020-06-29 15:38  小那  阅读(288)  评论(0编辑  收藏  举报