【微信小程序】canvasToTempFilePath遇到的问题

在微信小程序开发中,经常需要将绘制好的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));
  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值