微信小程序如何利用 canvas一键生成海报并保存到本地?纯前端完成

  • Post author:
  • Post category:小程序




微信小程序如何利用 canvas一键生成海报并保存到本地?纯前端完成

摘要:今天项目中遇到生成带二维码的图片,并可以保存到本地发到朋友圈。于是网上各种搜索查看,终于完美解决,特此总结一下,如果需要请做参考。

**先来看一下效果:**点击按钮生成带二维码的图片

在这里插入图片描述


代码如下:

wxml:

<!-- 模态对话框 -->
<view class="mask" catchtouchmove="preventTouchMove" wx:if="{{showModal}}" bindtap='closeModalDlg'></view>

<view class="canvas-box" hidden="{{showModal == false}}">
  <canvas style=" width:600rpx;height:980rpx;position:fixed;top:40rpx;left:75rpx; " canvas-id="mycanvas" />
</view>
<view class="share-wrap" wx:if="{{showModal}}">
  <view class="shareFriendsCircle" bindtap='saveImg'>分享朋友圈</view>
  <button class="shareFriends" open-type="share">分享给朋友</button>
</view>

wxss:

/* 模态框 */
.mask{
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0;
    left: 0;
    background: #000;
    z-index: 9000;
    opacity: 0.7;
}
.modalDlg{
    width: 500rpx;
    height: 620rpx;
    position: fixed;
    top: 50%;
    left: 5%;
    z-index: 99;
    margin: -370rpx 85rpx;
    background-color: #fff;
    border-radius: 8rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
}

/* canvas绘图 */
.canvas-box{
  width:0rpx;
  height:0rpx;
  overflow: hidden;
  position: fixed;
  left:0rpx;
  bottom:30rpx;
  z-index: 9999;
}
.share-wrap{
  width:600rpx;
  height:70rpx;
  position: absolute;
  left:75rpx;
  bottom:15%;
  z-index:9999;
  display: flex;
  justify-content: space-between;
  color:#fff;
}
.shareFriendsCircle{
  width:220rpx;
  height:100%;
  display: flex;
  align-items: center;
  justify-content: center;
  border:1rpx solid #fff;
  border-radius: 10rpx;
  font-size: 32rpx;
}
.shareFriends{
  width:220rpx;
  height:100%;
  display: flex;
  align-items: center;
  justify-content: center;
  border:1rpx solid #fff;
  border-radius: 10rpx;
  font-size: 32rpx;
}
button{
  margin:0rpx;
  padding:0rpx;
  background-color: rgba(0, 0, 0, 0);
  color:#fff;
}
.button-hover{
  color:#fff;
  background-color:rgba(0, 0, 0, 0);
}

js:

//请求后台接口获取头像 昵称 二维码图片 (有一些其他数据在里面没有摘出来)
request_mine() { 
    var $this = this;
    $http.post('my/index')
      .then(res => {
        var resObj = res.data;
        if (resObj.code == 1) {
          //成功回调
         
          $this.data.userInfo = resObj.data.userInfo;
          $this.data.store_has_many = resObj.data.userInfo.store_has_many
          $this.setData({
            nickname: resObj.data.userInfo.nickname,
            unread: resObj.data.userInfo.unread,
            store_has_many: resObj.data.userInfo.store_has_many
          })
          //转化头像图片地址(canvas不能绘制网络图片,所以调用api 把网路图片转换为本地路径,下同)
          if (typeof $this.data.userInfo.avatar === 'string') {
            wx.getImageInfo({ //  小程序网路图片转换为本地路径API
              src: $this.data.userInfo.avatar,
              success: function(res) {
                $this.data.switch1 = 1
                $this.data.userInfo.avatar = res.path
              },
              fail(err) {

                console.log(err)
              }
            })
          }

          // //获取背景图片
          $this.data.userInfo.invite_bg_img = app.globalData.imgUrl + $this.data.userInfo.invite_bg_img
          if (typeof $this.data.userInfo.invite_bg_img === 'string') {
            wx.getImageInfo({ //  小程序API
              src: $this.data.userInfo.invite_bg_img,
              success: function(res) {
                console.log(res.path)
                $this.data.switch2 = 1
                $this.data.userInfo.invite_bg_img = res.path
              },
              fail(err) {
                console.log($this.data.userInfo.invite_bg_img)
                console.log(err)
              }
            })
          }
          //获取二维码图片地址
          if ($this.data.userInfo.invitation_code_img) {
            $this.data.userInfo.invitation_code_img = app.globalData.localImgUrl + $this.data.userInfo.invitation_code_img
            if (typeof $this.data.userInfo.invitation_code_img === 'string') {
              wx.getImageInfo({ //  小程序API
                src: $this.data.userInfo.invitation_code_img,
                success: function(res) {
                  $this.data.switch3 = 1
                  $this.data.userInfo.invitation_code_img = res.path

                },
                fail(err) {
                
                }
              })
            }
          }
        }
      }).catch(err => {
        //异常回调
        console.log('请求失败,异常回调');
      });
  },
	
	//绘制海报
  createNewImg: function() {
    var $this = this
    var width
    var height
    wx.getSystemInfo({
      success(res) {
        width = res.screenWidth
        height = res.screenHeight
      }
    })
    var ctx = wx.createCanvasContext('mycanvas');
    var path = $this.data.userInfo.invite_bg_img; //背景图片
    var path2 = $this.data.userInfo.avatar //头像图片
    var name = $this.data.userInfo.nickname
    var invite_code = $this.data.userInfo.invite_code
    ctx.drawImage(path, 0, 0, 0.8 * width, 0.58 * height); //绘制图片模板的背景图片
    ctx.drawImage(path2, 30, 20, 60, 60); // 绘制头像
    //绘制昵称
    ctx.setFontSize(16);
    ctx.setFillStyle('#fff');
    ctx.fillText(name, 110, 35);
    ctx.stroke();
    //绘制邀请码
    ctx.setFontSize(18);
    ctx.setFillStyle('#000');
    ctx.fillText(invite_code, 0.8 * width * 0.25, 0.58 * height * 0.82);
    ctx.stroke();
    var path1 = $this.data.userInfo.invitation_code_img //二维码图片
    ctx.drawImage(path1, 0.8 * width * 0.7, 0.58 * height * 0.72, 0.8 * width * 0.25, 0.8 * width * 0.25); //绘制图片模板的二维码
    ctx.draw(true, () => {
      var that = this
      wx.canvasToTempFilePath({
        canvasId: 'mycanvas',
        success: res => {
          that.data.haibaoImg = res.tempFilePath
        }
      })
    })
  },

	//点击按钮生成海报
  erWeiMa: function() {
    var $this = this;
    var store_has_many = $this.data.store_has_many || [];
    if ($this.data.userInfo.invitation_code_img == null) { //没有生成二维码
      $http.post('my/setQrcode')
        .then(res => {
          $this.request_mine() //重新请求数据
        }).catch(err => {
          //异常回调
          console.log('请求失败,异常回调');
        });
    }
    if (store_has_many.length > 0) {
      if (store_has_many[0].auditstatus == 'paid_the_money') {
        if ($this.data.switch1 == 1 && $this.data.switch2 == 1 && $this.data.switch3 == 1) {
          $this.createNewImg()
          $this.setData({
            showModal: true
          })
        } else {
          wx.showToast({
            title: '生成中',
            icon: 'loading',
            duration: 1500
          })
          setTimeout(function() { //生成海报较慢需要添加一个定时器
            $this.createNewImg()
            $this.setData({
              showModal: true
            })
          }, 1500)
        }

      } else if (store_has_many[0].auditstatus == 'in_the_review') {
        wx.showToast({
          title: '审核中',
          image: '../../images/warn.png',
          duration: 1000
        })
      } else if (store_has_many[0].auditstatus == 'wait_the_review') {
        wx.showToast({
          title: '待审核',
          image: '../../images/warn.png',
          duration: 1000
        })
      } else if (store_has_many[0].auditstatus == 'pass_the_audit') {
        wx.showToast({
          title: '审核通过',
          image: '../../images/warn.png',
          duration: 1000
        })
      }
    } else {
      wx.showToast({
        title: '店铺未认证',
        image: '../../images/warn.png',
        duration: 1000
      })
    }
  },

  // 点击分享到朋友圈按钮 把生成的海报保存到本地
  saveImg: function() {
    var that = this
    wx.saveImageToPhotosAlbum({
      filePath: that.data.haibaoImg,
      success(res) {
        wx.showToast({
          title: '保存成功',
        });
      },
      fail(res) {
        console.log(res)
      }
    })
  },


前端进阶精选:点此去



版权声明:本文为qq_43327305原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。