0%

微信小程序 Canvas 真机导出图片到临时文件失败解决方案

微信小程序 Canvas 真机导出图片报错 canvasToTempFilePath:fail invalid viewId

设备信息:

1
2
3
4
设备信息:iPhone 13
系统版本:iOS 17.0
终端类型:微信 iOS 客户端
微信版本:8.0.40

原代码片段:

1
2
3
4
5
6
7
8
9
10
let canvas = wx.createOffscreenCanvas({type: '2d', width: 500, height: 500});
let ctx = canvas.getContext('2d');
ctx.fillStyle = '#ffffff';
ctx.fillRect(0, 0, canvas.width, canvas.height);
wx.canvasToTempFilePath({
canvas: canvas,
fileType: 'jpg',
success: console.log,
fail: console.error
})

解决方案及代码片段:

  1. 将画布内容导出为 Base64 字符串
  2. 将 Base64 字符串转成 ArrayBuffer 对象
  3. 将 ArrayBuffer 对象写入文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
let canvas = wx.createOffscreenCanvas({type: '2d', width: 500, height: 500});
let ctx = canvas.getContext('2d');
ctx.fillStyle = '#ffffff';
ctx.fillRect(0, 0, canvas.width, canvas.height);

const base64Data = canvas.toDataURL();
const currentTime = +new Date;
const filePath = `${wx.env.USER_DATA_PATH}/temp_image_${currentTime}.png`;
const data = wx.base64ToArrayBuffer(base64Data.substring(base64Data.indexOf(',') + 1));
wx.getFileSystemManager().writeFile({
filePath,
data,
encoding: 'utf-8',
success: console.log,
fail: console.error
});

Canvas 2d 报错 toTempFilePath:fail invalid viewid?? 瓦力|🇨🇳 的回答 - 微信开放社区