Canvas.getContext
JS
RenderingContext Canvas.getContext(string contextType, Object contextAttribute)获取画布对象的绘图上下文
同一个画布只能获取到一种绘图上下文
- 当使用 webgl 或 webgl2 上下文时:
- 当前绘图上下文对应的画布能够显示在屏幕上
- 若存在多个画布,其他的画布再去获取 webgl 绘图上下文,会返回空对象
- 由于 WebGL 的绘制与屏幕的宽高有关,所以当前渲染上下文对应的画布的 width 与 height 属性无法被修改
- 当使用 2d 上下文时:
- 通过当前绘图上下文绘制的内容,只能被存储在内存中
- 当前绘图上下文对应的画布的 width 与 height 属性可以被修改
参数
- string contextType: 需要获取的上下文类型,合法值如下
contextType 合法值说明:
| 值 | 说明 |
|---|---|
| 2d | 2d 绘图上下文 |
| webgl | webgl 绘图上下文 |
| experimental-webgl | webgl 绘图上下文 |
| webgl2 | webgl2 绘图上下文 |
| experimental-webgl2 | webgl2 绘图上下文 |
- Object contextAttributes: webgl 或 webgl2 上下文属性。对
contextType为2d时无效
contextAttributes 的属性说明:
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| alpha | boolean | true | 是否包含 alpha 缓冲区 |
| depth | boolean | true | 如果这个值为 true 绘制缓冲区包含一个深度至少为16位的缓冲区 |
| stencil | boolean | true | 如果这个值为 true 绘制缓冲区包含一个深度至少为8位的模版缓冲区 |
| antialias | boolean | false | 是否开启抗锯齿 |
| preserveDrawingBuffer | boolean | false | 如果这个值为 true 缓冲区将不会被清除,会保存下来,直到被清除或被使用者覆盖 |
返回值
- RenderingContext: 绘图上下文