Skip to content

Canvas.getContext

JS
    RenderingContext Canvas.getContext(string contextType, Object contextAttribute)

获取画布对象的绘图上下文

同一个画布只能获取到一种绘图上下文

  • 当使用 webgl 或 webgl2 上下文时:
    1. 当前绘图上下文对应的画布能够显示在屏幕上
    2. 若存在多个画布,其他的画布再去获取 webgl 绘图上下文,会返回空对象
    3. 由于 WebGL 的绘制与屏幕的宽高有关,所以当前渲染上下文对应的画布的 width 与 height 属性无法被修改
  • 当使用 2d 上下文时:
    1. 通过当前绘图上下文绘制的内容,只能被存储在内存中
    2. 当前绘图上下文对应的画布的 width 与 height 属性可以被修改

参数

  • string contextType: 需要获取的上下文类型,合法值如下

contextType 合法值说明:

说明
2d2d 绘图上下文
webglwebgl 绘图上下文
experimental-webglwebgl 绘图上下文
webgl2webgl2 绘图上下文
experimental-webgl2webgl2 绘图上下文
  • Object contextAttributes: webgl 或 webgl2 上下文属性。对 contextType2d 时无效

contextAttributes 的属性说明:

属性类型默认值说明
alphabooleantrue是否包含 alpha 缓冲区
depthbooleantrue如果这个值为 true 绘制缓冲区包含一个深度至少为16位的缓冲区
stencilbooleantrue如果这个值为 true 绘制缓冲区包含一个深度至少为8位的模版缓冲区
antialiasbooleanfalse是否开启抗锯齿
preserveDrawingBufferbooleanfalse如果这个值为 true 缓冲区将不会被清除,会保存下来,直到被清除或被使用者覆盖

返回值

  • RenderingContext: 绘图上下文