由于离屏 canvas的文档比较粗糙,新版的canvas文档对RenderingContext的方法比较缺失,离屏canvas写个demo搞了很久才出来,记录一下。
代码片段:https://developers.weixin.qq.com/s/Nuz9y5mr7Ky4
const app = getApp()
Page({
data: {},
onLoad: async function () {
// 创建离屏 2D canvas 实例
const offCanvas = wx.createOffscreenCanvas({type: '2d', width: 300, height: 300})
// 获取 context。注意这里必须要与创建时的 type 一致
const context = offCanvas.getContext('2d')
// 创建一个图片
const image = offCanvas.createImage()
// 等待图片加载
await new Promise(resolve => {
image.onload = resolve
image.src = './car.png' // 要加载的图片 url
})
// 把图片画到离屏 canvas 上
context.clearRect(0, 0, 300, 300)
context.drawImage(image, 0, 0, 105, 42)
context.fillText('MINA', 100, 100)
// 获取画完后的数据
const imgData = context.getImageData(0, 0, 300, 300)
this.imgData = imgData;
// 通过 SelectorQuery 获取 Canvas 节点
wx.createSelectorQuery()
.select('#canvas')
.fields({
node: true,
size: true,
})
.exec(this.init.bind(this))
},
init(res) {
const canvas = res[0].node
const ctx = canvas.getContext('2d')
ctx.font = '20px'
ctx.fillText('Hello', 20, 20)
// 将offCanvas生成的图片数据放入canvas中
ctx.putImageData(this.imgData, 0, 0);
},
})