小程序wx.canvasToTempFilePath压缩图片出现Uncaught (in promise) undefined错误

小程序使用wx.canvasToTempFilePath传入jpeg的图片就会报错:Uncaught (in promise) undefined
jpg和png的图片测试了没问题。这个压缩的太n了,整了一天都没整出来.


            fileList.map((item, idx) => {
                compressList[idx] = new Promise((resolve, reject) => {
                    wx.createSelectorQuery().select('#imageCanvas').fields({
                        node: true,
                        size: true
                    }).exec((res) => {
                        const canvas = res[0].node;
                        const ctx = canvas.getContext('2d')
                        const image = canvas.createImage()
                        image.src = item.url
                        image.onload = () => {
                            let ratio = 2
                            let canvasWidth = image.width
                            let canvasHeight = image.height
                            while (canvasWidth > 500 && canvasHeight > 500) {
                                canvasWidth = Math.trunc(res.width / ratio)
                                canvasHeight = Math.trunc(res.height / ratio)
                                ratio++
                            }
                            canvas.width = canvasWidth
                            canvas.height= canvasHeight
                            ctx.fillRect(0, 0, canvasWidth, canvasHeight)
                            ctx.drawImage(image, 0, 0, canvasWidth, canvasHeight)
                            
                            wx.canvasToTempFilePath({
                                canvas,
                                quality: 0.5,
                                fileType: 'jpg',
                                width: canvasWidth / 2, //canvas的宽高(生成图片的范围)
                                heght: canvasHeight / 2,
                                destWidth: (canvasWidth / 2) * wx.getWindowInfo().pixelRatio,
                                destHeight: (canvasHeight / 2) * wx.getWindowInfo().pixelRatio,
                                success: (res) => {
                                    console.log(res);
                                    resolve(res.tempFilePath)
                                },
                                fail: (res) => {
                                    reject()
                                }
                            })
                        }
                    })
                }).then(result => result)
            })

在微信开发者工具,右边详情里,把基础库版本调低试一下

该回答引用GPTᴼᴾᴱᴺᴬᴵ
根据您提供的代码,问题可能出在以下几个方面:

  1. 图片加载失败
    在使用canvas绘制图片之前,需要确保图片已经加载完成,否则绘制的结果可能为空白。您可以在加载图片时添加错误处理,确保图片加载成功后再进行绘制。

  2. 图片格式不支持
    根据您提供的代码,使用wx.canvasToTempFilePath传入jpeg的图片会报错。这可能是因为小程序不支持将canvas绘制的jpeg图片转为临时文件路径。您可以尝试将fileType设置为'png'或'bmp',看是否能够正常生成临时文件路径。

  3. 参数设置不正确
    在使用wx.canvasToTempFilePath时,需要正确设置width、height、destWidth、destHeight等参数,确保生成的图片大小和质量符合要求。您可以参考官方文档中的参数说明,检查您的参数设置是否正确。