基础库 2.16.1 开始支持,低版本需做兼容处理。
微信小程序插件:支持,需要微信小程序基础库版本不低于 2.16.1
微信 Windows 版:支持
微信 Mac 版:支持
微信 鸿蒙 OS 版:支持
相关文档: 画布指南、canvas 组件介绍
功能描述
创建离屏 canvas 实例
参数
object object
| 属性 | 类型 | 默认值 | 必填 | 说明 |
| type | string | webgl | 否 | 创建的离屏 canvas 类型 |
| | 合法值 | 说明 | | webgl | webgl类型上下文 | | 2d | 2d类型上下文 |
|
| width | number | | 否 | 画布宽度 |
| height | number | | 否 | 画布高度 |
| compInst | Component | | 否 | 在自定义组件下,当前组件实例的 this |
number width
画布宽度
number height
画布高度
Object this
在自定义组件下,当前组件实例的 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)
离屏 Canvas 类型不可混用
由于 webgl canvas 和 2d canvas 的底层实现方式不同,因此必须要在调用 wx.createOffscreenCanvas 时提前指定类型。
指定类型后,离屏 canvas getContext(type) 调用不允许混用,如不能对 webgl canvas 调用 getContext('2d')。
同样的,不同类型 canvas 调用 createImage 创建的图片对象也不支持混用,使用时请注意尽量使用 canvas 自身的 createImage 创建图片对象。
离屏 webgl canvas 支持作为参数传递给 wx.createMediaRecorder, 离屏 2d canvas 暂不支持。
旧版 createOffscreenCanvas
旧版函数签名为 wx.createOffscreenCanvas(width: number, height: number, this: object): OffscreenCanvas,从基础库 2.7.0 开始支持
从基础库 2.16.1 开始改为 wx.createOffscreenCanvas(options: object): OffscreenCanvas,向下兼容旧版入参。
但需注意旧版入参只能创建 webgl 类型,如需创建 2d 类型则必须使用新版。