let that = this
let imageInfo = await App.wxp.getImageInfo({
src: "https://xxx.com/files/sharePoster.jpg"
});
console.log("图片信息", imageInfo);
if (imageInfo.path) {
// 创建离屏画布
let canvas = wx.createOffscreenCanvas({
type: '2d',
width: imageInfo.width,
height: imageInfo.height
});
console.log("canvas", canvas);
let context = canvas.getContext('2d')
// 创建海报图片
const sharePoster = canvas.createImage()
sharePoster.src = imageInfo.path
sharePoster.onload = e => {
// 把图片画到离屏 canvas 上
context.clearRect(0,0, canvas.width, canvas.height);
context.drawImage(sharePoster, 0, 0, imageInfo.width, imageInfo.height, 0, 0, imageInfo.width, imageInfo.height);
let base64 = context.canvas.toDataURL('image/png');
console.log(base64); // base64可以正常显示图片
that.setData({
src: base64,
invite: true
})
setTimeout(() => {
// 报错:Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or HTMLImageElement or SVGImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap or OffscreenCanvas)'
wx.canvasToTempFilePath({
canvas: canvas, // canvas type="2d" 时使用该属性
complete(res) {
console.log("tempFilePath", res);
}
}, that) // 有无this都会报错
}, 1000);
}
}
小程序调用wx.canvasToTempFilePath报错Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or HTMLImageElement or SVGImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap or OffscreenCanvas)
切换一下基础库就行了。我真是服了,排查了一天,最后发现是基础库问题。
开始用的是 2.18.1,不管用什么样的姿势,都是报这个错。
后面换成 2.20.3,好了。
再切回 2.18.1,又报错。
可以断定是基础库的问题了。
要求一个图片类型,检查一下参数值
context.canvas.toDataURL(‘image/png’)转为base64都可以正常显示画布内容。