webgl2 方法解析: getContext()

在 WebGL2 中,getContext() 方法用于获取一个 WebGL2RenderingContext 对象,它是 WebGL2 的核心接口,提供了 OpenGL ES 3.0 的渲染上下文。

获取 WebGL2 上下文

要获取 WebGL2 上下文,需要在 HTML 的 <canvas> 元素上调用 getContext() 方法,并传入 "webgl2" 作为参数:

ini 复制代码
const canvas = document.getElementById("myCanvas");
const gl = canvas.getContext("webgl2");

如果浏览器不支持 WebGL2,getContext("webgl2") 将返回 null

上下文属性

在创建 WebGL2 上下文时,还可以通过第二个参数传递一个上下文属性对象来配置上下文的行为。例如:

arduino 复制代码
const gl = canvas.getContext("webgl2", {
  alpha: false, // 禁用 alpha 通道
  depth: true, // 启用深度缓冲区
  antialias: true, // 启用抗锯齿
});

常见的上下文属性包括:

  • alpha:是否启用 alpha 通道。
  • depth:是否启用深度缓冲区。
  • stencil:是否启用模板缓冲区。
  • antialias:是否启用抗锯齿。
  • premultipliedAlpha:是否使用预乘 alpha。

兼容性

WebGL2 是 WebGL 的扩展版本,基于 OpenGL ES 3.0。它在 WebGL 1 的基础上增加了许多新功能,例如更复杂的着色器支持、更高效的缓冲区操作等。目前,WebGL2 在大多数现代浏览器中得到了支持,但一些旧版本的浏览器(如 IE 和部分旧版本的 Safari)可能不支持。

示例

以下是一个完整的示例代码:

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>WebGL2 Uniform Buffer Example</title>
  <style>
    canvas {
      width: 800px;
      height: 600px;
    }
  </style>
</head>
<body>
  <canvas id="canvas"></canvas>
  <script>
    // 获取 WebGL2 上下文
    const canvas = document.getElementById('canvas');
    const gl = canvas.getContext('webgl2');
    if (!gl) {
      throw new Error('WebGL2 is not supported by your browser.');
    }
​
    // 顶点着色器代码
    const vertexShaderSource = `#version 300 es
      in vec4 a_position;
      void main() {
        gl_Position = a_position;
      }
    `;
​
    // 片段着色器代码
    const fragmentShaderSource = `#version 300 es
      precision highp float;
      out vec4 outColor;
      void main() {
        outColor = vec4(1.0, 0.0, 0.0, 1.0);
      }
    `;
​
    // 创建着色器
    function createShader(gl, type, source) {
      const shader = gl.createShader(type);
      gl.shaderSource(shader, source);
      gl.compileShader(shader);
      if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
        console.error('Shader compile failed with:', gl.getShaderInfoLog(shader));
        gl.deleteShader(shader);
        return null;
      }
      return shader;
    }
​
    // 创建程序
    const vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexShaderSource);
    const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentShaderSource);
    const program = gl.createProgram();
    gl.attachShader(program, vertexShader);
    gl.attachShader(program, fragmentShader);
    gl.linkProgram(program);
    if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
      throw new Error('link falsed! ');
    }
    gl.useProgram(program);
​
    // 创建顶点缓冲区
    const positionBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
    const positions = new Float32Array([
      -0.5, -0.5, 0.0,
       0.5, -0.5, 0.0,
       0.0,  0.5, 0.0
    ]);
    gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW);
​
    // 设置顶点属性指针
    const positionLocation = gl.getAttribLocation(program, 'a_position');
    gl.enableVertexAttribArray(positionLocation);
    gl.vertexAttribPointer(positionLocation, 3, gl.FLOAT, false, 0, 0);
​
    // 渲染循环
    function render() {
      gl.clearColor(0.0, 0.0, 0.0, 1.0);
      gl.clear(gl.COLOR_BUFFER_BIT);
​
      gl.drawArrays(gl.TRIANGLES, 0, 3);
​
      requestAnimationFrame(render);
    }
​
    render();
  </script>
</body>
</html>
相关推荐
烛阴6 小时前
Mix - Bilinear Interpolation
前端·webgl
魂断蓝桥66618 小时前
使用three.js实现3D消防,消防管线,消防教育(课一:消防给水系统01)
webgl·数字孪生·three.js·3d建筑·物联网3d·3d定位、三维室内定位、3d建筑·3d消防·消防演习模拟·消防给水系统
烛阴1 天前
Mix
前端·webgl
烛阴2 天前
Tile Pattern
前端·webgl
平行云4 天前
实时云渲染将UE像素流嵌入业务系统,实现二维管理系统与数字孪生三维可视化程序的无缝交互
unity·webgl·数字孪生·云渲染·虚幻引擎·实时云渲染·像素流送
烛阴6 天前
Mod
前端·webgl
烛阴7 天前
Fract - Grid
前端·webgl
cos8 天前
从像素到粒子:p5.js 图像转动态粒子的设计与实现
前端·javascript·webgl
山海鲸可视化11 天前
模型材质一键替换~轻松还原多种三维场景
webgl·数字孪生·材质·3d模型·三维渲染
Perfumere13 天前
【WebGPU学习杂记】Uniform和Stroage的区别和适用场景
前端·webgl