微信小程序canvas坑canvasToTempFilePath坑图片为空,封装canvas为组件

真的是花了一天的时间去踩坑,网上好多帖子,我基本都踩了一遍,真的是好多坑啊,泪流满面.........

需求大致描述:用户选择图片拍照或者相册,2张图片拼成1张,因为是多个地方使用,所以我想着封装成一个组件,在别的页面进行引入,拼之前每张图片都有做处理的(如:裁剪、旋转)然后得到的图片数组

首先说一下我大概有报的一些错误吧:

  1. canvasToTempFilePath:fail canvas is empty
  2. An SelectorQuery call is ignored because no proper page or component is foun

  3. Cannot read property '__wxWebviewId__?

  4. 还有些报错,百度的太多,找不到了,笑哭,最有印象的就是这几个

直接上代码,更加直观:为了方便复制,图片最下面有贴代码,可能有理解没那么好,写的有误的地方,欢迎各位大佬指出

 

 

 

 最后最后,我还是加了定时器,保证万无一失

 

 canvasFn() {
      let ww, hh
      const query = this.createSelectorQuery() 
      query
        .select('#canvasStyle')
        .boundingClientRect((data) => {
          ww = data.width
          hh = data.height
          var ctx = wx.createCanvasContext('myCanvas', this) 
          ctx.setFillStyle = '#FFFFFF'
          uni.showLoading({
            title: '正在生成中...',
            mask: true,
          })
          
          let that = this 
          wx.getImageInfo({
            src: that.listImg[0].img,        
            success(res) {
              ctx.drawImage(res.path, 0, 0, 60, 60)        
              setTimeout(()=>{
          
ctx.draw(true, () => {
                wx.canvasToTempFilePath(
                  {
                    fileType: 'jpg',
                    canvasId: 'myCanvas', 
                    success: (res) => {
                      uni.hideLoading() 
                      that.base64 = res.tempFilePath 
                      console.log('res.tempFilePath:', res)
                    },
                  },
                  that  
                )
              })
        },500)
            },
          })
        })
        .exec()
    },

 

posted @ 2022-04-16 18:40  温柔本肉  阅读(3288)  评论(0编辑  收藏  举报