canvas绘制海报及点击保存海报

1.canvas绘制海报

  createcanvas() {
    let that = this,
      windowW = that.data.windowW
    const query = wx.createSelectorQuery() //获取对象实例
    query.select('#Canvas') //选择获取canvas对象实例
      .fields({ //获取节点的相关信息。需要获取的字段在fields中指定。
        node: true,
        size: true
      })
      .exec((res) => {
        console.log(res);
        const canvas = res[0].node //拿到canvas对象
        that.setData({ //这里保存canvas对象是因为下面保存相片要用这个对象
          canvas
        })
        const ctx = canvas.getContext('2d') //返回用于在画布上绘图的环境
        const dpr = that.data.pixelRatio //拿到设备像素比
        canvas.width = res[0].width * dpr //缩放画布
        canvas.height = res[0].height * dpr
        ctx.scale(dpr, dpr)

        //1、绘制背景图(本地图片)
        const imgbg = canvas.createImage()
        imgbg.onload = (e) => {
          console.log(1);
          // ctx.drawImage(imgbg, 24, 110, 260, 430) //50
          ctx.drawImage(imgbg, that.fitSize(0), that.fitSize(0), that.fitSize(255), that.fitSize(422))

          //2、绘制图片及文字
          const imggood = canvas.createImage()
          imggood.onload = (e) => {
            console.log(2);
            // ctx.drawImage(imggood, 40,182, 228, 248)
            ctx.drawImage(imggood, that.fitSize(16), that.fitSize(72), that.fitSize(223), that.fitSize(248))
            let str = '今天是儿童节,亦是世界牛奶日,祝大小朋友节日快乐,祝大小朋友节日快乐!'
            let chr = str.split(""); //这个方法是将一个字符串分割成字符串数组
            let temp = "";
            let row = [];
            ctx.font = `${parseInt(that.fitSize(12))}px FZZhunYuan-director`;
            ctx.fillStyle = '#4E4E4E';
            console.log(ctx.measureText(str)); //查看文本长度
            //如果文字过长设置为两行
            for (let a = 0; a < chr.length; a++) {
              if (ctx.measureText(temp).width < (that.fitSize(140))) {
                temp += chr[a];
              } else {
                a--; //这里添加了a-- 是为了防止字符丢失,效果图中有对比
                row.push(temp);
                temp = "";
              }
            }
            row.push(temp);
            if (row.length > 2) {
              let rowCut = row.slice(0, 2);
              let rowPart = rowCut[1];
              let test = "";
              let empty = [];
              for (let a = 0; a < rowPart.length; a++) {
                if (ctx.measureText(test).width < (that.fitSize(140))) {
                  test += rowPart[a];
                } else {
                  break;
                }
              }
              empty.push(test);
              let group = empty[0] + "..." //这里只显示两行,超出的用...表示
              rowCut.splice(1, 1, group);
              row = rowCut;
            }
            for (let b = 0; b < row.length; b++) {
              // console.log(row[b]);
              // ctx.fillText(row[b], 0.23 * windowW, (windowW - 100) * 1 + b * 20); 
              ctx.fillText(row[b], that.fitSize(28), (windowW - 35) * 1 + b * 16);
            }
            //3、绘制小程序二维码图片
            const imgqrcode = canvas.createImage()
            imgqrcode.onload = (e) => {
              console.log(5);
              //绘制二维码
              ctx.drawImage(imgqrcode, that.fitSize(189), that.fitSize(323), that.fitSize(50), that.fitSize(45))
            }
            imgqrcode.src = 'https://campaigncdn.herdsric.com/a2/invitenow/qrcode.png'
          }
          imggood.src = 'https://campaigncdn.herdsric.com/a2/invitenow/dbtp.png'
        }
        imgbg.src = 'https://campaigncdn.herdsric.com/a2/invitenow/bj_share.png'
      })
  },
 try {
      const res = wx.getSystemInfoSync()
      this.setData({
        windowW: res.windowWidth,
        windowH: res.windowHeight,
        pixelRatio: res.pixelRatio
      })
      // console.log('41', res.windowHeight, res.windowWidth, res.windowHeight / res.windowWidth)
      if (res.windowHeight / res.windowWidth < 1.8) {
        this.setData({
          finishSrceen: true
        })
      } else if (res.windowHeight / res.windowWidth <= 1.61) {
        this.setData({
          smallsSrceen: true
        })
      }
    } catch (error) {
      this.setData({
        smallSrceen: false,
        finishSrceen: false
      })
    }

2.点击保存海报

 savepic() {
      let that = this
      wx.showLoading({
        title: '正在保存',
        mask: true
      })
      wx.canvasToTempFilePath({
        canvas: that.data.canvas,
        x: (that.fitSize(60)),
        y: (that.fitSize(0)),
        width: (that.fitSize(255)),
        height: (that.fitSize(422)),
        success: function (res) {
          console.log(res, '成功');
          wx.hideLoading()
          let tempFilePath = res.tempFilePath
          that.checkWritePhotosAlbum(tempFilePath)
        },
        fail: function (err) {
          console.log(err, '失败')
          wx.showToast({
            title: '保存失败!请重新保存',
            icon: 'none'
          })
          wx.hideLoading()
        }
      })
  
    },

3.查看是否有相册权限

   checkWritePhotosAlbum(filePath) {
      let that = this
      wx.getSetting({
        success(res) {
          if (!res.authSetting['scope.writePhotosAlbum']) {
            wx.authorize({
              scope: 'scope.writePhotosAlbum',
              success() {
                that.saveToPhoto(filePath)
              },
              fail() {
                wx.openSetting({
                  success(res) {
                    if (res.authSetting['scope.writePhotosAlbum']) {
                      that.saveToPhoto(filePath)
                    }
                  },
                  fail(res) {
                    wx.showToast({
                      title: '您没有授权,无法保存到相册!',
                      icon: 'none'
                    })
                  }
                })
              }
            })
          } else {
            that.saveToPhoto(filePath)
          }
        }
      })
    },

3.保存到相册

fitSize(coordinate) {
    let that = this;
    let windowW = that.data.windowW; //这个windowWidth指的是该设备宽度,可以onLoad监听页面加载中获取
    let v = 375 / windowW; //375是设计稿的大小,得到的v值是:设计稿和设备宽度的比例关系,也可理解成在设计稿的大小基础上放大或缩小的倍数
    return coordinate / v; //返回的是当前坐标值或者大小与v的比例
  },

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值