WebGL 简介:使用 JavaScript 构建 3D 图形应用程序

王林
王林 转载
2023-08-30 18:29:13 779浏览

WebGL 简介:使用 JavaScript 构建 3D 图形应用程序

WebGL(Web 图形库)是一种 JavaScript API,允许开发人员在 Web 浏览器中创建和渲染交互式 3D 图形。它在 JavaScript 编程语言和底层图形硬件之间架起了一座桥梁,能够创建身临其境且视觉震撼的 Web 应用程序。在本文中,我们将探讨 WebGL 的基础知识并演示如何使用 JavaScript 构建简单的 3D 图形应用程序。

WebGL 基础知识

WebGL 基于 OpenGL ES(嵌入式系统)标准,该标准广泛应用于游戏行业和其他图形密集型应用程序。它利用计算机 GPU(图形处理单元)的强大功能来执行复杂的渲染任务,从而可以在浏览器环境中创建高性能 3D 图形。

要开始使用 WebGL,我们需要将 WebGL 上下文包含在 HTML 画布元素中。 canvas 元素充当渲染图形的容器。以下是如何设置基本 WebGL 环境的示例。

示例

<!DOCTYPE html>
<html>
   <head>
      <title>WebGL Example</title>
      <style>
         body {
            margin: 0;
            overflow: hidden;
         }
         canvas {
            display: block;
         }
      </style>
   </head>
   <body>
      <canvas id="myCanvas"></canvas>
      <script>
         const canvas = document.getElementById("myCanvas");
         const gl = canvas.getContext("webgl");
         if (!gl) {
            alert("Unable to initialise WebGL. Your browser may not support it.");
         }
      </script>
   </body>
</html>

说明

在上面的代码中,我们首先创建一个id为“myCanvas”的canvas元素。然后,我们使用 JavaScript 获取对 canvas 元素的引用,并通过使用参数“webgl”调用 getContext 方法来请求 WebGL 上下文。如果浏览器支持WebGL,则getContext方法将返回一个WebGLRenderingContext对象,我们可以将其存储在gl变量中。如果不支持 WebGL,则会显示警告消息。

渲染 3D 图形

一旦我们获得了 WebGL 上下文,我们就可以开始在画布上渲染 3D 图形。 WebGL 的工作原理是在 GPU 上执行一系列 OpenGL ES 着色器程序,这些程序执行必要的计算来转换和渲染 3D 场景的顶点和像素。

着色器程序是一组在 GPU 上运行的指令。 WebGL中有两种类型的着色器:顶点着色器和片段着色器。顶点着色器处理 3D 对象的每个顶点,转换其位置、颜色和其他属性。另一方面,片段着色器确定几何形状内每个像素的颜色。

要渲染一个简单的 3D 对象,我们需要定义其几何形状并指定将使用的着色器程序。以下示例演示了如何使用 WebGL 渲染旋转立方体。

示例

<!DOCTYPE html>
<html>
   <head>
      <title>WebGL Example</title>
      <style>
         body {
            margin: 0;
            overflow: hidden;
         }
         canvas {
            display: block;
         }
      </style>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/gl-matrix/2.8.1/gl-matrix.js"></script>
   </head>
   <body>
      <canvas id="myCanvas"></canvas>
      <script>
         const canvas = document.getElementById("myCanvas");
         const gl = canvas.getContext("webgl");
         if (!gl) {
            alert("Unable to initialise WebGL. Your browser may not support it.");
         }

         // Define the vertex shader
         const vertexShaderSource = `
         attribute vec3 aPosition;
         uniform mat4 uModelViewMatrix;
         uniform mat4 uProjectionMatrix;

         void main() {
            gl_Position = uProjectionMatrix * uModelViewMatrix * vec4(aPosition, 1.0);
         }
         `;

         // Define the fragment shader
         const fragmentShaderSource = `
         precision mediump float;

         void main() {
            gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
         }
         `;

         // Create the vertex shader
         const vertexShader = gl.createShader(gl.VERTEX_SHADER);
         gl.shaderSource(vertexShader, vertexShaderSource);
         gl.compileShader(vertexShader);

         // Create the fragment shader
         const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
         gl.shaderSource(fragmentShader, fragmentShaderSource);
         gl.compileShader(fragmentShader);

         // Create the shader program
         const shaderProgram = gl.createProgram();
         gl.attachShader(shaderProgram, vertexShader);
         gl.attachShader(shaderProgram, fragmentShader);
         gl.linkProgram(shaderProgram);
         gl.useProgram(shaderProgram);

         // Set up the geometry
         const positions = [
            -1.0, -1.0, -1.0,
            1.0, -1.0, -1.0,
            1.0, 1.0, -1.0,
            -1.0, 1.0, -1.0,
            -1.0, -1.0, 1.0,
            1.0, -1.0, 1.0,
            1.0, 1.0, 1.0,
            -1.0, 1.0, 1.0
         ];
         const vertexBuffer = gl.createBuffer();
         gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
         gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);
         const positionAttributeLocation = gl.getAttribLocation(shaderProgram, "aPosition");
         gl.enableVertexAttribArray(positionAttributeLocation);
         gl.vertexAttribPointer(positionAttributeLocation, 3, gl.FLOAT, false, 0, 0);

         // Set up the transformation matrices
         const modelViewMatrixLocation = gl.getUniformLocation(shaderProgram, "uModelViewMatrix");
         const projectionMatrixLocation = gl.getUniformLocation(shaderProgram, "uProjectionMatrix");
         const modelViewMatrix = mat4.create();
         const projectionMatrix = mat4.create();
         mat4.translate(modelViewMatrix, modelViewMatrix, [0.0, 0.0, -6.0]);
         mat4.perspective(projectionMatrix, Math.PI / 4, canvas.width / canvas.height, 0.1, 100.0);
         gl.uniformMatrix4fv(modelViewMatrixLocation, false, modelViewMatrix);
         gl.uniformMatrix4fv(projectionMatrixLocation, false, projectionMatrix);

         // Render the cube
         gl.drawArrays(gl.LINE_LOOP, 0, 4);
         gl.drawArrays(gl.LINE_LOOP, 4, 4);
         gl.drawArrays(gl.LINES, 0, 2);
         gl.drawArrays(gl.LINES, 2, 2);
         gl.drawArrays(gl.LINES, 4, 2);
         gl.drawArrays(gl.LINES, 6, 2);
      </script>
   </body>
</html>

说明

上面显示的代码演示了 WebGL 程序的基本结构。首先定义顶点着色器和片段着色器,它们分别控制每个顶点和像素的位置和颜色。然后着色器被编译并附加到着色器程序。

接下来,通过创建立方体的顶点位置数组来定义几何形状。创建顶点缓冲区对象 (VBO) 并用顶点数据填充。位置属性已启用并配置为从缓冲区读取顶点数据。

设置变换矩阵(模型视图和投影)来控制 3D 对象的位置和视角。这些矩阵使用统一变量传递给着色器。

最后,通过使用适当的参数调用 gl.drawArrays 函数来渲染立方体,以指定渲染模式(例如,线或线循环)和要绘制的顶点数。

结论

WebGL 是一个功能强大的 API,可将 3D 图形引入网络。它允许开发人员创建视觉上令人惊叹的交互式应用程序,并直接在浏览器中运行。在本文中,我们介绍了 WebGL 的基础知识,并演示了如何使用 JavaScript 构建简单的 3D 图形应用程序。

以上就是WebGL 简介:使用 JavaScript 构建 3D 图形应用程序的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除