Home > Web Front-end > JS Tutorial > Introduction to WebGL: Build 3D graphics applications with JavaScript

Introduction to WebGL: Build 3D graphics applications with JavaScript

王林
Release: 2023-08-30 18:29:13
forward
1403 people have browsed it

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

WebGL (Web Graphics Library) is a JavaScript API that allows developers to create and render interactive 3D graphics in a web browser. It bridges the gap between the JavaScript programming language and the underlying graphics hardware, enabling the creation of immersive and visually stunning web applications. In this article, we'll explore the basics of WebGL and demonstrate how to build a simple 3D graphics application using JavaScript.

WebGL Basics

WebGL is based on the OpenGL ES (Embedded Systems) standard, which is widely used in the gaming industry and other graphics-intensive applications. It harnesses the power of your computer's GPU (graphics processing unit) to perform complex rendering tasks, allowing you to create high-performance 3D graphics in a browser environment.

To start using WebGL, we need to include the WebGL context in an HTML canvas element. The canvas element acts as a container for rendering graphics. Here's an example of how to set up a basic WebGL environment.

Example

<!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>
Copy after login

illustrate

In the above code, we first create a canvas element with the id "myCanvas". We then use JavaScript to get a reference to the canvas element and request the WebGL context by calling the getContext method with the parameter "webgl". If the browser supports WebGL, the getContext method will return a WebGLRenderingContext object, which we can store in the gl variable. If WebGL is not supported, a warning message is displayed.

Rendering 3D Graphics

Once we have obtained the WebGL context, we can start rendering 3D graphics on the canvas. WebGL works by executing a series of OpenGL ES shader programs on the GPU, which perform the necessary calculations to transform and render the vertices and pixels of a 3D scene.

A shader program is a set of instructions that run on the GPU. There are two types of shaders in WebGL: vertex shaders and fragment shaders. Vertex shaders process each vertex of a 3D object, transforming its position, color, and other properties. Fragment shaders, on the other hand, determine the color of each pixel within the geometry.

To render a simple 3D object, we need to define its geometry and specify the shader program that will be used. The following example demonstrates how to render a rotating cube using WebGL.

Example

<!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>
Copy after login

illustrate

The code shown above demonstrates the basic structure of a WebGL program. First define the vertex shader and fragment shader, which control the position and color of each vertex and pixel respectively. The shader is then compiled and attached to the shader program.

Next, define the geometry by creating an array of vertex positions of the cube. Create a vertex buffer object (VBO) and fill it with vertex data. The position attribute is enabled and configured to read vertex data from a buffer.

Set transformation matrices (model view and projection) to control the position and perspective of 3D objects. These matrices are passed to the shader using uniform variables.

Finally, the cube is rendered by calling the gl.drawArrays function with the appropriate parameters to specify the rendering mode (for example, line or line loop) and the number of vertices to be drawn.

in conclusion

WebGL is a powerful API that brings 3D graphics to the web. It allows developers to create visually stunning interactive applications and run them directly in the browser. In this article, we introduced the basics of WebGL and demonstrated how to build a simple 3D graphics application using JavaScript.

The above is the detailed content of Introduction to WebGL: Build 3D graphics applications with JavaScript. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template