WebGL has a track record of being one of Javascript’s more complex API’s. As a web developer intrigued by all that’s interactive, I decided to dive into WebGL’s MDN documentation. I’ve worked with Three.js which abstracts a lot of the hardships of WebGL but I couldn’t help but open up the hood!
The goal of this deep dive was to see if I could make sense of the documentation enough to explain it in simpler terms. Disclaimer — I’ve worked with Three.js and have a bit of knowledge in 3D graphic terminology and patterns. I’ll be sure to explain these concepts if they apply in any way.
To start, we’re going to focus on the creation of a triangle. The reason for this is to establish an understanding of the parts needed to set up webGL.
To get a feel of what will be covered, here are the steps we’ll be going through.
Set up the HTML canvas
Get the WebGL context
Clear the canvas color and set a new one
Create an array of triangle (x,y )coordinates
Add vertex and fragment shader code
Process and compile the shader code
Create a webGL program
Create and bind buffers to the webGL program
Use the program
Link the GPU information to the CPU
Draw out the triangle
Setup HTML Canvas
- Create a folder called “RenderTriangle”
- In that folder create an index.html and main.js file
Within the index.html file add the following code:
index.js
<meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <canvas id="canvas"></canvas> <script src="main.js"></script>
is the entry point for rendering the WebGL context
We set up the basic HTML code and link the main.js file.
In the main.js file we will access the canvas id to render webGL content.
Prepare the HTML Canvas
Within the main.js file add the following code which prepares the HTML canvas:
main.js
// get canvas const canvas = document.getElementById("canvas"); // set width and height of canvas canvas.width = window.innerWidth; canvas.height = window.innerHeight; // get the webgl context const gl = canvas.getContext("webgl2");
Get the HTML canvas by id and store it in a variable called “canvas” (you can use any name).
Set the canvas.width and canvas.height properties of the canvas by accessing the window.innerWidth and window.innerHeight. This sets the rendered display to the size of the browser window.
Get the WebGL context using canvas.getContext(“webgl2”) and store it in a variable called “gl”.
Clear Color
main.js
gl.clearColor(0.1, 0.2, 0.3, 1.0); gl.clear(gl.DEPTH_BUFFER_BIT | gl.COLOR_BUFFER_BIT);
Before writing any webGL program you need to set the background color of your canvas. WebGL has two methods for making this happen.
clearColor() — is a method that sets a specific background color. It’s called “clearColor” because when you render WebGL into the HTML canvas, CSS sets the background to the color black. When you call clearColor(), it clears the default color and sets whatever color you want. We can see this below.
Note: The clearColor() has 4 parameters (r, g, b, a)
clear() — after clearColor() is called and an explicit background color is set,
**clear()** must be called to “clear” or reset the buffers to the preset values (the buffers are temporary storage for color and depth information).
The clear() method is one of the drawing methods which means it’s the method that actually renders the color. Without calling the clear() method the canvas won’t show the clearColor. The clear() parameter options are,
are gl.COLOR_BUFFER_BIT, gl.DEPTH_BUFFER_BIT, or gl.STENCIL_BUFFER_BIT.
In the code below you can add multiple parameters to reset in different scenarios.
gl.DEPTH_BUFFER_BIT — indicates buffers for pixel depth information
gl.COLOR_BUFFER_BIT — indicates the buffers for pixel color information
Set Triangle Coordinates
main.js
// set position coordinates for shape const triangleCoords = [0.0, -1.0, 0.0, 1.0, 1.0, 1.0];
Once the the background is set we can set the coordinates needed to create the triangle. The coordinates are stored in an array as (x, y) coordinates.
The below array holds 3-point coordinates. These points connect to form the triangle.
0.0, -1.0
0.0 , 1.0
1.0, 1.0
Adding Vertex and Fragment Shaders
main.js
const vertexShader = `#version 300 es precision mediump float; in vec2 position; void main() { gl_Position = vec4(position.x, position.y, 0.0, 1.0); //x,y,z,w } `; const fragmentShader = `#version 300 es precision mediump float; out vec4 color; void main () { color = vec4(0.0,0.0,1.0,1.0); //r,g,b,a } `;
After creating a variable for the triangle coordinates, we can set up the shaders.
A shader is a program written in OpenGL ES Shading Language. The program takes position and color information about each vertice point. This information is what’s needed to render geometry.
There are two types of shaders functions that are needed to draw webgl content, the vertex shader and fragment shader
*vertex shader *— The vertex shader function uses position information to render each pixel. Per every render, the vertex shader function runs on each vertex. The vertex shader then transforms each vertex from it’s original coordinates to WebGL coordinates. Each transformed vertex is then saved to the gl_Position variable in the vertex shader program.
*fragment shader *— The fragment shader function is called once for every pixel on a shape to be drawn. This occurs after the vertex shader runs. The fragment shader determines how the color of each pixel and “texel (pixel within a texture)” should be applied. The fragment shader color is saved in the gl_FragColor variable in the fragment shader program.
In the code above we are creating both a vertexShader and fragmentShader constant and storing the shader code in them. The Book of Shaders is a great resource for learning how to write GLSL code.
Processing the Vertex and Fragment Shaders
main.js
// process vertex shader const shader = gl.createShader(gl.VERTEX_SHADER); gl.shaderSource(shader, vertexShader); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { console.log(gl.getShaderInfoLog(vertexShader)); } // process fragment shader const shader = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(shader, fragmentShader); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { console.log(gl.getShaderInfoLog(fragmentShader)); }
Now that we wrote the shader code (GLSL), we need to create the shader. The shader code still needs to compile. To do this we call the following functions:
createShader() — This creates the shader within the WebGL context
shaderSource() — This takes the GLSL source code that we wrote and sets it into the webGLShader object that was created with createShader.
compileShader() — This compiles the GLSL shader program into data for the WebGLProgram.
The code above processes the vertex and fragment shaders to eventually compile into the WebGLProgram.
Note: An if conditional is added to check if both shaders have compiled properly. If not, an info log will appear. Debugging can be tricky in WebGL so adding these checks is a must.
Creating a WebGL Program
main.js
const program = gl.createProgram(); // Attach pre-existing shaders gl.attachShader(program, vertexShader); gl.attachShader(program, fragmentShader); gl.linkProgram(program); if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { const info = gl.getProgramInfoLog(program); throw "Could not compile WebGL program. \n\n${info}"; }
Let’s review the code above:
After compiling the vertexShader and fragmentShader, we can now create a WebGLProgram. A WebGLProgram is an object that holds the compiled vertexShader and fragmentShader.
createProgram() — Creates and initializes the WebGLProgram
attachShader() — This method attaches the shader to the webGLProgram
linkProgram() — This method links the program object with the shader objects
Lastly, we need to make a conditional check to see if the program is running properly. We do this with the gl.getProgramParameter.
Create and Bind the Buffers
Now that the WebGL Program is created and the shader programs are linked to it, it’s time to create the buffers. What are buffers?
To simplify it as much as possible, buffers are objects that store vertices and colors. Buffers don’t have any methods or properties that are accessible. Instead, the WebGL context has it’s own methods for handling buffers.
Buffer — “a temporary storage location for data that’s being moved from one place to another”
-wikipedia
We need to create a buffer so that we can store our triangle colors and vertices.
To do this we add the following:
main.js
const buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(triangleCoords), gl.STATIC_DRAW); gl.bindBuffer(gl.ARRAY_BUFFER, null);
In the code above we’re creating a buffer (or temporary storage object) using the createBuffer() method. Then we store it in a constant. Now that we have a buffer object we need to bind it to a target. There are several different target but since we’re storing coordinates in an array we will be using the gl.ARRAY_BUFFER.
To bind the buffer to a target, we use gl.bindBuffer() and pass in the gl.ARRAY_BUFFER (target) and the buffer itself as parameters.
The next step would be to use gl.bufferData() which creates the data store. gl.bufferData() takes the following parameters:
target — gl.ARRAY_BUFFER
data — new Float32Array(triangleCoords)
usage (draw type) — gl.STATIC_DRAW
Lastly, we unbind the buffer from the target to reduce side effects.
Use Program
main.js
gl.useProgram(program);
Once the buffer creation and binding is complete, we can now call the method that sets the WebGLProgram to the rendering state.
Link GPU and CPU
As we get closer to the final step, we need to talk about attributes.
In WebGL, vertex data is stored in a special variable called attributes. attributes are only available to the javascript program and the vertex shader. To access the attributes variable we need to first get the location of the attributes from the GPU. The GPU uses an index to reference the location of the attributes.
main.js
// get index that holds the triangle position information const position = gl.getAttribLocation(obj.program, obj.gpuVariable); gl.enableVertexAttribArray(position); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.vertexAttribPointer(position, 2, gl.FLOAT, obj.normalize, obj.stride, obj.offset);
Let’s review the code above:
Since we’re rendering a triangle we need the index of the position variable that we set in the vertex shader. We do this using the gl.getAttribLocation() method. By passing in the WebGL program and the position variable name (from the vertex shader) we can get the position attribute’s index.
Next, we need to use the gl.enableVertexAttribArray() method and pass in the position index that we just obtained. This will enable the attributes` storage so we can access it.
We will then rebind our buffer using gl.bindBuffer() and pass in the gl.ARRAY_BUFFER and buffer parameters (the same as when we created the buffers before). Remember in the “Create and Bind the Buffers” section we set the buffer to null to avoid side effects.
When we binded the buffer to the gl.ARRAY_BUFFER we are now able to store our attributes in a specific order. gl.vertexAttribPointer() allows us to do that.
By using gl.vertexAttribPointer() we can pass in the attributes we’d like to store in a specific order. The parameters are ordered first to last.
The gl.vertexAttribPointer is a more complex concept that may take some additional research. You can think of it as a method that allows you to store your attributes in the vertex buffer object in a specific order of your choosing.
Sometimes 3D geometry already has a certain format in which the geometry information is set. vertexAttribPointer comes in handy if you need to make modifications to how that geometry information is organized.
Draw Triangle
main.js
gl.drawArrays(gl.TRIANGLES, 0, 3);
Lastly, we can use the gl.drawArrays method to render the triangle. There are other draw methods, but since our vertices are in an array, this method should be used.
gl.drawArrays() takes three parameters:
mode — which specifies the type of primitive to render. (in this case were rendering a triangle)
first — specifies the starting index in the array of vector points (our triangle coordinates). In this case it’s 0.
count — specifies the number of indices to be rendered. ( since it's a triangle we’re rendering 3 indices)
Note: For more complex geometry with a lot of vertices you can use **triangleCoords.length / 2 **to ****get how many indices your geometry has.
Finally, your triangle should be rendered to the screen! Let’s review the steps.
Set up the HTML canvas
Get the WebGL context
Clear the canvas color and set a new one
Create an array of triangle (x,y )coordinates
Add vertex and fragment shader code
Process and compile the shader code
Create a webGL program
Create and bind buffers to the webGL program
Use the program
Link the GPU information to the CPU
Draw out the triangle
The API is a complex one so there’s still a lot to learn but understanding this setup has given me a better foundation.
// Set up the HTML canvas const canvas = document.getElementById("canvas"); canvas.width = window.innerWidth; canvas.height = window.innerHeight; // get the webgl context const gl = canvas.getContext("webgl2"); // Clear the canvas color and set a new one gl.clearColor(0.1, 0.2, 0.3, 1.0); gl.clear(gl.DEPTH_BUFFER_BIT | gl.COLOR_BUFFER_BIT); // Create an array of triangle (x,y )coordinates const triangleCoords = [0.0, -1.0, 0.0, 1.0, 1.0, 1.0]; // Add vertex and fragment shader code const vertexShader = `#version 300 es precision mediump float; in vec2 position; void main() { gl_Position = vec4(position.x, position.y, 0.0, 1.0); //x,y,z,w } `; const fragmentShader = `#version 300 es precision mediump float; out vec4 color; void main () { color = vec4(0.0,0.0,1.0,1.0); //r,g,b,a } `; // Process and compile the shader code const vShader = gl.createShader(gl.VERTEX_SHADER); gl.shaderSource(vShader, vertexShader); gl.compileShader(vShader); if (!gl.getShaderParameter(vShader, gl.COMPILE_STATUS)) { console.log(gl.getShaderInfoLog(vertexShader)); } const fShader = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(fShader, fragmentShader); gl.compileShader(fShader); if (!gl.getShaderParameter(fShader, gl.COMPILE_STATUS)) { console.log(gl.getShaderInfoLog(fragmentShader)); } // Create a webGL program const program = gl.createProgram(); // Link the GPU information to the CPU gl.attachShader(program, vShader); gl.attachShader(program, fShader); gl.linkProgram(program); if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { const info = gl.getProgramInfoLog(program); throw "Could not compile WebGL program. \n\n${info}"; } // Create and bind buffers to the webGL program const buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(triangleCoords), gl.STATIC_DRAW); gl.bindBuffer(gl.ARRAY_BUFFER, null); // Use the program gl.useProgram(program); // Link the GPU information to the CPU const position = gl.getAttribLocation(program, "position"); gl.enableVertexAttribArray(position); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.vertexAttribPointer(position, 2, gl.FLOAT, gl.FALSE, 0, 0); // render triangle gl.drawArrays(gl.TRIANGLES, 0, 3);
Here are some invaluable references to help understand this material better.
https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API
https://www.udemy.com/course/webgl-internals/
https://webglfundamentals.org/
以上是分解 WebGL 三角形设置的详细内容。更多信息请关注PHP中文网其他相关文章!

JavaScript字符串替换方法详解及常见问题解答 本文将探讨两种在JavaScript中替换字符串字符的方法:在JavaScript代码内部替换和在网页HTML内部替换。 在JavaScript代码内部替换字符串 最直接的方法是使用replace()方法: str = str.replace("find","replace"); 该方法仅替换第一个匹配项。要替换所有匹配项,需使用正则表达式并添加全局标志g: str = str.replace(/fi

因此,在这里,您准备好了解所有称为Ajax的东西。但是,到底是什么? AJAX一词是指用于创建动态,交互式Web内容的一系列宽松的技术。 Ajax一词,最初由Jesse J创造

10款趣味横生的jQuery游戏插件,让您的网站更具吸引力,提升用户粘性!虽然Flash仍然是开发休闲网页游戏的最佳软件,但jQuery也能创造出令人惊喜的效果,虽然无法与纯动作Flash游戏媲美,但在某些情况下,您也能在浏览器中获得意想不到的乐趣。 jQuery井字棋游戏 游戏编程的“Hello world”,现在有了jQuery版本。 源码 jQuery疯狂填词游戏 这是一个填空游戏,由于不知道单词的上下文,可能会产生一些古怪的结果。 源码 jQuery扫雷游戏

本教程演示了如何使用jQuery创建迷人的视差背景效果。 我们将构建一个带有分层图像的标题横幅,从而创造出令人惊叹的视觉深度。 更新的插件可与JQuery 1.6.4及更高版本一起使用。 下载

本文讨论了在浏览器中优化JavaScript性能的策略,重点是减少执行时间并最大程度地减少对页面负载速度的影响。

Matter.js是一个用JavaScript编写的2D刚体物理引擎。此库可以帮助您轻松地在浏览器中模拟2D物理。它提供了许多功能,例如创建刚体并为其分配质量、面积或密度等物理属性的能力。您还可以模拟不同类型的碰撞和力,例如重力摩擦力。 Matter.js支持所有主流浏览器。此外,它也适用于移动设备,因为它可以检测触摸并具有响应能力。所有这些功能都使其值得您投入时间学习如何使用该引擎,因为这样您就可以轻松创建基于物理的2D游戏或模拟。在本教程中,我将介绍此库的基础知识,包括其安装和用法,并提供一

本文演示了如何使用jQuery和ajax自动每5秒自动刷新DIV的内容。 该示例从RSS提要中获取并显示了最新的博客文章以及最后的刷新时间戳。 加载图像是选择


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

Dreamweaver CS6
视觉化网页开发工具

WebStorm Mac版
好用的JavaScript开发工具