# [OffscreenCanvas](/miniprogram/dev/api/canvas/OffscreenCanvas) wx.createOffscreenCanvas(object object, number width, number height, Object this)

> 基础库 2.16.1 开始支持，低版本需做[兼容处理](1003706)。

> __小程序插件__：支持，需要小程序基础库版本不低于 [2.16.1](1003706)
> 
> __微信 Windows 版__：支持
> 
> __微信 Mac 版__：支持
> 
> __微信 鸿蒙 OS 版__：支持

> 相关文档: [画布指南](/miniprogram/dev/framework/ability/canvas.md)、[canvas 组件介绍](/miniprogram/dev/component/canvas.md)

## 功能描述

创建离屏 canvas 实例

## 参数

### object object


```json
[
  {
    "属性": "type",
    "类型": "string",
    "默认值": "webgl",
    "必填": "否",
    "说明": "创建的离屏 canvas 类型",
    "子项": [
      {
        "合法值": "webgl",
        "说明": "webgl类型上下文"
      },
      {
        "合法值": "2d",
        "说明": "2d类型上下文"
      }
    ]
  },
  {
    "属性": "width",
    "类型": "number",
    "默认值": "",
    "必填": "否",
    "说明": "画布宽度"
  },
  {
    "属性": "height",
    "类型": "number",
    "默认值": "",
    "必填": "否",
    "说明": "画布高度"
  },
  {
    "属性": "compInst",
    "类型": "Component",
    "默认值": "",
    "必填": "否",
    "说明": "在自定义组件下，当前组件实例的 this"
  }
]
```

### number width

画布宽度

### number height

画布高度

### Object this

在自定义组件下，当前组件实例的 this

## 返回值

### [OffscreenCanvas](/miniprogram/dev/api/canvas/OffscreenCanvas)

## 示例代码

```javascript

  // 创建离屏 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` 创建图片对象。

## 与 MediaRecorder 结合

离屏 webgl canvas 支持作为参数传递给 [`wx.createMediaRecorder`](/miniprogram/dev/api/media/media-recorder/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 类型则必须使用新版。
