小程序画布创建离屏canvas实例wx.createOffscreenCanvas
OffscreenCanvas wx.createOffscreenCanvas(object object, number width, number height, Object this)
创建离屏 canvas 实例
基础库 2.16.1 开始支持,低版本需做兼容处理。
小程序插件:支持,需要小程序基础库版本不低于 2.16.1
微信 Windows 版:支持
微信 Mac 版:支持
参数
object object
属性 类型 默认值 必填 说明
type string webgl 否 创建的离屏 canvas 类型
合法值 说明
webgl webgl类型上下文
2d 2d类型上下文
width number 否 画布宽度
height number 否 画布高度
compInst Component 否 在自定义组件下,当前组件实例的 this
返回值
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 = IMAGE_URL // 要加载的图片 url
})
// 把图片画到离屏 canvas 上
context.clearRect(0, 0, 300, 150)
context.drawImage(image, 0, 0, 300, 150)
// 获取画完后的数据
const imgData = context.getImageData(0, 0, 300, 150)