在微信小程序开发中,经常需要将绘制好的canvas保存到本地,这就需要调用canvasToTempFilePath将canvas画布转为本地临时文件。遇到过的问题如下:
1.create bitmap failed
2.fail canvas is empty
在这里插入图片描述
这个问题就是canvas还没画为空拿不到转化的临时路径
在这里插入图片描述在这里插入图片描述
跟上述问题一样,我在开发过程中也遇到过拿到了tempFilePath临时路径,但是展示不出来。

原因:调取 wx.canvasToTempFilePath 接口获取不到canvas
(1)检查canvasId是否对应
canvas控件中用到的跟canvasToTempFilePath用到的canvasId要一致
(2)检查canvas画布是否被隐藏
可能在canvas画布上用到了hidden属性用来隐藏画布
可以让画布的位置在屏幕之外

<canvas canvas-id='canvasId' style="width: {{ cWidth }}px; height: {{ cHeight }}px;position: absolute;left: -1000rpx;top: -1000rpx;"></canvas>

(3)检查wx.canvasToTempFilePath方法是否在draw()的回调里面
注意:因为draw的回调函数是异步的,在调用canvasToTempFilePath方法时可能图片还没有生成完,所以要适当的加一些时间延迟。多次尝试ios手机可不加定时器,安卓手机基本上都要加,延迟的时间跟手机的性能有关,性能较弱的安卓机出现问题的概率比较大,延迟的时间试过200还是会偶现问题,设置为500基本有效。

var ctx = wx.createCanvasContext('canvasId')
ctx.drawImage(rep.path, 0, 0, canvasWidth, canvasHeight);
ctx.draw(false,setTimeout(() => {
  wx.canvasToTempFilePath({
    canvasId: 'canvasId',
    fileType: 'jpg',
    success(res) {
      console.log(res.tempFilePath);
    },
    fail(error) {
      console.log(error);
    }
  })
},500));

(4)检查是否在自定义组件中使用,如果是则要传入当前组件实例的this
在这里插入图片描述

//绘制图片
let that = this
var ctx = wx.createCanvasContext('canvasId',that)
ctx.drawImage(rep.path, 0, 0, canvasWidth, canvasHeight);
ctx.draw(false,setTimeout(() => {
  wx.canvasToTempFilePath({
    canvasId: 'canvasId',
    fileType: 'jpg',
    success(res) {
      console.log(res.tempFilePath);
    },
    fail(error) {
      console.log(error);
    }
  },that)
},500));
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐