小程序ios报错 canvasToTempFilePath:fail invalid viewId的解决办法

1,125 阅读1分钟

场景:

用canvas画好图片之后,调用wx.canvasToTempFilePath,开发工具和安卓机正常,ios报错canvasToTempFilePath:fail invalid viewId

解决:

1、调用Canvas.toDataURL先转成base64 2、将base64转成本地临时路劲

 let base64 = canvas.toDataURL();
  const time = new Date().getTime();
  const imgPath = wx.env.USER_DATA_PATH + "/poster" + time + "share" + ".png";
  //如果图片字符串不含要清空的前缀,可以不执行下行代码.
  const imageData = base64.replace(/^data:image\/\w+;base64,/, "");
  const fs = wx.getFileSystemManager();
  fs.writeFileSync(imgPath, imageData, "base64");
  fs.close()
  // imgPath 就是临时路劲

注意

调用fs.writeFileSync后一定记得用 fs.unlink删掉,或者读取全部文件删掉

 const fs = wx.getFileSystemManager()

  const basepath = `${wx.env.USER_DATA_PATH}`

  fs.readdir({

    dirPath: basepath,/// 获取文件列表

    success(res) {
      console.log('全部临时文件')
      console.log(res)

      res.files.forEach((val) => { // 遍历文件列表里的数据
        fs.unlink({
          filePath: basepath + '/' + val
        });
      })

    },
    fail(err) {
      console.log('读取失败')
      console.log(err)

    }

  })