第一种情况
//wxml
//js
const query = wx.createSelectorQuery()
query.select('#mask')
.fields({ node: true, size: true })
.exec((res) => {
const canvas = res[0].node
const ctx = canvas.getContext('2d')
wx.getImageInfo({
src: 'xxx',//合法域名
success (res) {
//单独执行这两句报错
ctx.drawImage(res.path,0,0)
ctx.draw()
//单独执行这三句正常
ctx.setFillStyle('#50d2a6')
ctx.fillRect(0,0,100,100)
ctx.draw()
}
})
})
报错信息
Failed to execute drawImage on CanvasRenderingContext2D: The provided value is not of type (CSSImageValue or HT
MLImageElement or SVGImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap or OffscreenCanvas)
第二种情况
//wxml
//js
const ctx = wx.createCanvasContext('mask', this)
wx.getImageInfo({
src: 'xxx',//合法域名
success (res) {
//这单独执行两句不显示
ctx.drawImage(res.path,0,0)
ctx.draw()
//单独执行这三句也不显示
ctx.setFillStyle('#50d2a6')
ctx.fillRect(0,0,100,100)
ctx.draw()
}
})
另外drawImage()参数我dx,dy,dw,dh都传了试过,结果一样
2d绘制图片必须先用canvas.createImage加载图片后再绘制
为什么 type="2d"
后.exec((res) =>老是提示下面错误:
TypeError: Cannot read property 'createView' of undefined
问题已经解决,还是贴出来吧,毕竟在文档里没找到完整的说明和写法。
const query = wx.createSelectorQuery() query.select('#canvas') .fields({ node: true, size: true }) .exec((res) => { const canvas = res[0].node const ctx = canvas.getContext('2d') wx.getImageInfo({ src: 'xxx',//合法域名 success (res) { //js写法var image = new Image()会报错 //小程序api不支持js的Image构造方法 const image = canvas.createImage() image.src = res.path ctx.drawImage(image,0,0) } }) })