# Canvas.getContext(string contextType)
获取 Canvas 渲染上下文。
# 支持情况
| 项 | 说明 |
|---|---|
| 兼容性 | 兼容微信 |
# 语法
canvas.getContext(contextType)
# 参数
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| contextType | string | 是 | 上下文类型,合法值见下表 |
contextType 合法值
| 值 | 说明 |
|---|---|
'2d' | 2D 渲染上下文(CanvasRenderingContext2D) |
'webgl' | WebGL 1.0 渲染上下文(WebGLRenderingContext) |
'webgl2' | WebGL 2.0 渲染上下文(WebGL2RenderingContext) |
# 返回值
CanvasRenderingContext2D | WebGLRenderingContext | WebGL2RenderingContext — 对应类型的渲染上下文;同一 Canvas 多次调用返回同一实例。
# 示例代码
const canvas = mt.createCanvas()
// 2D 上下文
const ctx = canvas.getContext('2d')
ctx.fillStyle = '#ff0000'
ctx.fillRect(0, 0, 100, 100)
// WebGL 上下文
const gl = canvas.getContext('webgl')
gl.clearColor(0, 0, 0, 1)
gl.clear(gl.COLOR_BUFFER_BIT)
# 与微信差异
无差异(行为与微信小游戏一致)。