只是type="2d"的画布
一、把type、id、canvas-id通通加上,选择器加上in(app.proxy),app.proxy相当于二代的this,记住!它全部都要。
- TypeError: Cannot read property ‘node’ of null
- Cannot read property ‘getContext’ of null
<canvas type="2d" id="myCanvas" canvas-id="myCanvas"></canvas>
const app = getCurrentInstance()
const query = uni.createSelectorQuery().in(app.proxy)
query.select('#myCanvas').fields({
node: true,
size: true
}).exec((res) => {
const canvas = res[0].node
const ctx = res[0].node.getContext('2d')
...
// outCanvas.value = canvas
// outCtx.value = ctx , 给外部响应式变量赋值的,请往下看
})
二、尽管绘制文字等操作可以使用外部响应式变量outCtx.value.fillText()方法,但绘制图片ctx.drawImage()时,仍要获取画布实例和上下文对象,请交给里面的ctx干活。
3.TypeError: Cannot read property ‘createImage’ of undefined
4.TypeError: Cannot read property ‘nodeId’ of undefined
const drawImage = function(img, x, y, w, h) {
return new Promise((resolve, reject) => {
const query = uni.createSelectorQuery().in(app.proxy)
query.select('#myCanvas').fields({
node: true,
size: true
}).exec((res) => {
const canvas = res[0].node
const ctx = res[0].node.getContext('2d')
const image = canvas.createImage()
image.onload = () => {
ctx.drawImage(image, x, y, w, h)
resolve(true)
}
image.onerror = (err) => {
resolve(false)
}
image.src = img
})
})
}
三、你仍然不信邪,然后你尝试了以下方法,发现可以在开发者工具上显示图片,即将大功告成,但是我遇到了真机绘图静默失败的情况。要不,您再试试看。
const image = unref(outCanvas).createImage()
image.onload = ()=>{ ctx.value.drawImage(image,x,y,w,h)}
image.srcset = img
四、准备变成一张漂亮的海报时,记住当初的山盟海誓。回过头来,还是里面的ctx靠谱。
- canvasToTempFilePath: fail canvas is empty
wx.canvasToTempFilePath(Object object, Object this)
| 属性 | 类型 | 必填 | 说明 |
|---|---|---|---|
| canvasId | string | 否 | 画布标识,传入 canvas 组件的 canvas-id |
| canvas | Object | 否 | 画布标识,传入 canvas 组件实例 (canvas type=“2d” 时使用该属性)。 |
const query = uni.createSelectorQuery().in(app.proxy)
query.select('#myCanvas').fields({
node: true,
size: true
}).exec((res) => {
const canvas = res[0].node
const ctx = res[0].node.getContext('2d')
uni.canvasToTempFilePath({
canvas: canvas,
fileType: 'png',
destWidth: 500,
destHeight: 500,
quality: 1,
success: (res) => {
console.log(res)
previewImgSrc.value = res.tempFilePath
// uni.previewImage({
// urls: [res.tempFilePath]
// })
},
fail: (err) => {
console.log(err)
}
}, app.proxy)
})
