小程序-海报下载

<canvas canvas-id="shareCanvas" style="position:absolute;left:-1000%;visibility:hidden;bottom:0;width:{{canvas_w}}px;height:{{canvas_h}}px;z-index:999;background:#fff;"></canvas>
  data: {
    openCanvas:false,//是否显示海报
    userIconUrl:'',
    canvas_w: '',
    canvas_h: '',
    pixelRatio_w: '',
    pixelRatio_h: '',
    pixelRatio:'',//像素比
    Ratio: '',//缩放比
    canvasimg: '',//生成的图片
    imgurl: '',
    allpromise:[]
  },

 

 
    
that.data.pixelRatio = wx.getSystemInfoSync().pixelRatio that.data.Ratio = 375 / wx.getSystemInfoSync().windowWidth wx.getSystemInfo({ //获取系统信息成功,将系统窗口的宽高赋给页面的宽高 success: function (res) { console.log(res) that.data.pixelRatio = res.pixelRatio that.data.Ratio = 375 / res.windowWidth that.data.pixelRatio_w = 746 / 750 let w = 746 / 375 * res.windowWidth let h = 1027 / 375 * res.windowWidth that.data.canvas_w=w that.data.canvas_h = h that.setData({ canvas_w:w, canvas_h:h, pixelRatio: res.pixelRatio }, function () { that.canvasbroast() }) } })

  



//获取图片信息
getimg(url) {
    return new Promise(function (resolve, reject) {
      wx.getImageInfo({
        src: url,
        success: function (res) {
          resolve(res);
        },
        fail: function (res) {
          reject(res)
        }
      })
    });
  },
  // 生成海报
  canvasbroast() {
    const that = this
    that.data.allpromise = []
    that.data.allpromise.push(that.getimg(that.data.imageUrl))
    that.data.allpromise.push(that.getimg(that.data.code))
    Promise.all(
      that.data.allpromise
    ).then(res => {
      const ctx = wx.createCanvasContext('shareCanvas')
      ctx.rect(0, 0, 590, 751)
      ctx.setFillStyle('#fff')
      ctx.fill()
      ctx.drawImage(res[0].path, 0, 0, 590, 556)
      ctx.setFillStyle('#333333')  // 文字颜色:黑色
      ctx.setFontSize(28)
      that.drawText(ctx, that.data.goodsName, 24, 608, 376, 38)
      that.drawwidth(ctx, '砍后仅需 ¥', '#FF5D07', 24, 24, '')
      if (that.data.activityMinPrice % 1 !== 0) {
        that.drawwidth(ctx, that.data.minactualint, '#FF5D07', 36, 148, '')
        let str_l = that.data.minactualint
        let str = that.data.minactualfloat
        let l = ctx.measureText(str_l[str_l.length - 1]).width;
        that.drawwidth(ctx, '.' + str, '#FF5D07', 24, 148 + l * str_l.length, true)
      } else {
        that.drawwidth(ctx, that.data.minactualint, '#FF5D07', 36, 148, '')
      }
      ctx.drawImage(res[1].path, 426, 588, 130, 130)
      ctx.drawImage(that.data.code, 426, 575, 134, 134)
      ctx.draw(false, () => {
        setTimeout(() => {
          wx.canvasToTempFilePath({
            x: 0,
            y: 0,
            width: 590/that.data.pixelRatio,
            height: 751/that.data.pixelRatio,
            destWidth: 590 * that.data.pixelRatio,
            destHeight: 751 * that.data.pixelRatio,
            canvasId: 'shareCanvas',
            quality: 1,
            success(res) {
              console.log(res.tempFilePath)
              // wx.saveImageToPhotosAlbum({
              //   filePath: res.tempFilePath[0],
              //   success(res) { }
              // })
              that.data.canvasimg = res.tempFilePath
            },
            fail: function (res) {
              console.log(res);
            }
          })
        })
      })
    })
  },
  //保存至相册
  save() {
    const that = this
    wx.showToast({
      title: '分享图片生成中...',
      icon: 'loading',
      duration: 3000
    });
    wx.authorize({
      scope: "scope.writePhotosAlbum",
      success() {
        setTimeout(() => {
          that.getsetting()
        }, 3000)
      },
      fail() {
        wx.showToast({
          title: '未获得相关权限,无法保存图片',
          icon: 'none',
          duration: 2000
        })
        that.getsetting()
      }
    })

  },
  getsetting() {
    const that = this
    wx.getSetting({
      success(res) {
        //这里判断是否有保存相册权限
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.showModal({
            title: '授权保存到相册',
            success: function (res) {
              if (res.confirm == false) {
                return false;
              }
              wx.openSetting({
                success(res) {
                  //如果再次拒绝则返回页面并提示
                  if (!res.authSetting['scope.writePhotosAlbum']) {
                    wx.showToast({
                      title: '无法获取图片存储权限,请手动开启授权',
                      duration: 3000,
                      icon: 'none'
                    })
                  } else {
                    wx.saveImageToPhotosAlbum({
                      filePath: that.data.canvasimg,
                      success(res) {
                        wx.showToast({
                          title: '保存成功',
                          icon: 'none',
                          duration: 1000
                        });
                      }
                    })
                  }
                }
              })
            }
          })
        } else {
          wx.saveImageToPhotosAlbum({
            filePath: that.data.canvasimg,
            success(res) {
              wx.showToast({
                title: '保存成功',
                icon: 'none',
                duration: 1000
              });
            }
          })
        }
      }
    })
  },
//绘制文本 drawwidth(ctx, text, color, font, leftWidth, left = "") { ctx.setFillStyle(color) // 文字颜色:黑色 ctx.setFontSize(font) if (!left) { ctx.fillText(text, leftWidth, 716) } else { ctx.fillText(text, leftWidth, 716) } },
//截取长文字 drawText(ctx, str, leftWidth, initHeight, canvasWidth, lineHeight) { let lineWidth = 0; let lastSubStrIndex = 0; //每次开始截取的字符串的索引 for (let i = 0; i < str.length; i++) { lineWidth += ctx.measureText(str[i]).width; if (lineWidth > canvasWidth) { if (initHeight <= 608) { ctx.fillText(str.substring(lastSubStrIndex, i), leftWidth, initHeight); //绘制截取部分 } else { ctx.fillText(str.substring(lastSubStrIndex, i - 2) + '...', leftWidth, initHeight); //绘制截取部分 } initHeight += 38; //16为字体的高度 lineWidth = 0; lastSubStrIndex = i; } if (i == str.length - 1) { //绘制剩余部分 ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight); } } }

  

/ that.data.Ratio
posted @ 2019-10-31 13:40  吴小样  阅读(32)  评论(0)    收藏  举报