小程序使用canvas生成海报,保存图片

752 阅读2分钟

使用canvas生成海报
在这里插入图片描述
wxml

<view>
    <canvas class="canvas" style="width: {{canvas_width}}px;height:{{canvas_height}}px;" canvas-id="mycanvas"></canvas>
    <view class="pop">
        <view class="popbg" bindtap="getclose"></view>
        <view class="popup">
            <view class="poster">
                <image src="{{canvas}}"></image>
            </view>
            <view class="save">
                <view class="down">
                    <image mode="widthFix" src="https://sucai.suoluomei.cn/sucai_zs/images/20200110105821-1.png">
                    </image>
                </view>
                <view bindtap="getsave">保存图片</view>
            </view>
        </view>
    </view>
</view>

wxss

.popbg {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  z-index: 10;
}

.popup {
  position: fixed;
  top: 10%;
  left: 50%;
  transform: translate(-50%);
  z-index: 100;
}

.poster {
  width: 700rpx;
  height: 900rpx;
  background: #fff;
  border-radius: 30rpx;
  overflow: hidden;
}

.save {
  margin: 40rpx auto 0;
  width: 340rpx;
  height: 70rpx;
  background: #0C6D4A;
  border-radius: 10rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.down {
  width: 50rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.save view:nth-child(2) {
  color: #fff;
  font-size: 28rpx;
  margin-left: 20rpx;
}

.canvas {
  position: absolute;
  top: -9999rpx;
  left: 0;
}

image {
  width: 100%;
  height: 100%;

}

js

data: {
    canvas: '',
    canvas_width: 700,
    canvas_height: 900,
    main: "https://sucai.suoluomei.cn/sucai_zs/images/20191209160052-2.png",
    logo: "https://sucai.suoluomei.cn/sucai_zs/images/20190919150508-logo.png",
    explain: "长按识别或保存图片",
    code: "http://sucai.suoluomei.cn/sucai_zs/images/20200526093044-%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20200526093016.png",
  },

onLoad: function (options) {
    var logo = this.data.logo
    var main = this.data.main
    var explain = this.data.explain
    var code = this.data.code
    this.getcanvas(logo, main, explain, code)
  },

  // 获取海报 画布设置宽700 高800 
  // 以此传入图标,主体图片,标题文字,小程序二维码
  getcanvas(logo, main, explain, code) {
    wx.showLoading({
      title: '加载中',
    })
    // 主图所需
    let primary = ""
    let primary_width = ""
    let primary_height = ""
    // logo所需
    let mark = ""
    let mark_width = ""
    let mark_height = ""
    // 小程序码所需
    let yard = ""
    let yard_width = ""
    let yard_height = ""
    // 用户头像
    let portrait = ""
    let portrait_width = ""
    let portrait_height = ""

    return new Promise((resolve, reject) => {
        // 海报主要图
        wx.getImageInfo({
          src: main,
          success: (res) => {
            primary = res.path
            primary_width = res.width
            primary_height = res.height
            if (res.errMsg == "getImageInfo:ok") {
              // 海报水印logo
              wx.getImageInfo({
                src: logo,
                success: (res) => {
                  mark = res.path
                  mark_width = res.width
                  mark_height = res.height
                  if (res.errMsg == "getImageInfo:ok") {
                    // 小程序码
                    wx.getImageInfo({
                      src: code,
                      success: (res) => {
                        yard = res.path
                        yard_width = res.width / 2
                        yard_height = res.height / 2
                        if (res.errMsg == "getImageInfo:ok") {
                          // 用户头像
                          wx.getUserInfo({
                            success: function (res) {
                              wx.getImageInfo({
                                src: res.userInfo.avatarUrl,
                                success: (res) => {
                                  portrait = res.path
                                  portrait_width = res.width
                                  portrait_height = res.height
                                  resolve(res)
                                }
                              })
                            }
                          })

                        }
                      },
                    })
                  }
                },
              })
            }
          },
        })
      })
      .then(res => {
        let ctx = wx.createCanvasContext('mycanvas')
        // 填充背景颜色
        ctx.rect(0, 0, this.data.canvas_width, this.data.canvas_height)
        ctx.setFillStyle('#fff')
        ctx.fill()
        // 用户头像
        ctx.save()
        ctx.beginPath()
        ctx.arc(75, 75, 45, 0, Math.PI * 2, false);
        ctx.stroke()
        ctx.clip();
        ctx.drawImage(portrait, 30, 30, 90, 90) //145为arc的90加110除以2
        ctx.restore()
        // 用户昵称
        ctx.setFontSize(28)
        ctx.setFillStyle('#000')
        ctx.fillText('倘若', mark_width + 50, mark_height + 30)

        // logo图片
        ctx.drawImage(mark, this.data.canvas_width - mark_width - 30, 30, mark_width, mark_height)
        // 主体图片
        ctx.drawImage(primary, this.data.canvas_width / 2 - primary_width / 2.4, 140, primary_width / 1.2, primary_height / 1.2)
        // 详情
        ctx.setFontSize(24)
        ctx.setTextAlign('center')
        ctx.setFillStyle('#666')
        ctx.fillText('你的好友分享给你的小程序', this.data.canvas_width / 2, 500)
        ctx.fillText(explain, this.data.canvas_width / 2, 550)
        
        // 小程序二维码
        ctx.drawImage(yard, this.data.canvas_width / 2 - yard_width / 2.4, 600, yard_width / 1.2, yard_height / 1.2)
        ctx.draw(true, setTimeout(() => {
          wx.canvasToTempFilePath({
            canvasId: 'mycanvas',
            success: (res) => {
              wx.hideLoading()
              console.log(res.tempFilePath)
              this.setData({
                canvas: res.tempFilePath
              })
            },
          }, this)
        }, 500))
      })
  },
  // 保存为图片
  getsave() {
    wx.getSetting({ //询问用户是否保存相册到本地
      success: (set) => {
        wx.saveImageToPhotosAlbum({
          filePath: this.data.canvas,
          success: (res) => {
            if (res.errMsg == "saveImageToPhotosAlbum:ok") {
              wx.showToast({
                title: '保存成功',
              });
              this.setData({
                show: 0
              })
            }
          }
        })
        //拒绝保存到本地的处理机制
        if (set.authSetting['scope.writePhotosAlbum'] == false) {
          wx.openSetting({
            success(set) {
              console.log(set)
            }
          })
        }
      }
    })
  },