基础库版本:2.16.1
报错内容:
VM1309 WAService.js:2 TypeError: 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)'
代码段:
// 创建离屏 2D canvas 实例
const canvas = wx.createOffscreenCanvas({type: '2d', width: 300, height: 150})
// 获取 context。注意这里必须要与创建时的 type 一致
const context = canvas.getContext('2d')
// 创建一个图片
const image = canvas.createImage()
// 等待图片加载
await new Promise(resolve => {
image.onload = resolve
image.src = 'http://1812.img.pp.sohu.com.cn/images/blog/2009/11/18/18/8/125b6560a6ag214.jpg' // 要加载的图片 url
})
// 把图片画到离屏 canvas 上
context.clearRect(0, 0, 300, 150)
context.drawImage(image, 0, 0, 300, 150)
wx.canvasToTempFilePath({
canvas: canvas,
quality: 1,
success: (res) => {
let filePath = res.tempFilePath; //获取图片地址
console.log("filePath:",filePath)
}
}, this)
离屏画布的方法好像还不是很好用,还是用wx.createSelectorQuery()解决了,只需要把画布组件置于屏幕外就行了
<canvas type="2d" id="canvas" style="width:400px; height:400px;position:fixed;left:100%;" ></canvas>