1. is the entry point for rendering the WebGL context

  2. We set up the basic HTML code and link the main.js file.

  3. 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 canvasconst canvas = document.getElementById(\\\"canvas\\\");// set width and height of canvascanvas.width = window.innerWidth;canvas.height = window.innerHeight;// get the webgl contextconst gl = canvas.getContext(\\\"webgl2\\\");
  1. Get the HTML canvas by id and store it in a variable called “canvas” (you can use any name).

  2. 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.

  3. 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.

  1. gl.DEPTH_BUFFER_BIT — indicates buffers for pixel depth information

  2. gl.COLOR_BUFFER_BIT — indicates the buffers for pixel color information

Set Triangle Coordinates

main.js

// set position coordinates for shapeconst 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 esprecision 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 esprecision 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 shaderconst 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 shaderconst 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 shadersgl.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:

targetgl.ARRAY_BUFFER
datanew 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 informationconst 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.

\\\"Breaking

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 canvasconst canvas = document.getElementById(\\\"canvas\\\");canvas.width = window.innerWidth;canvas.height = window.innerHeight;// get the webgl contextconst gl = canvas.getContext(\\\"webgl2\\\");// Clear the canvas color and set a new onegl.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 )coordinatesconst triangleCoords = [0.0, -1.0, 0.0, 1.0, 1.0, 1.0];// Add vertex and fragment shader codeconst vertexShader = `#version 300 esprecision 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 esprecision 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 codeconst 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 programconst program = gl.createProgram();// Link the GPU information to the CPUgl.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 programconst 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 programgl.useProgram(program);// Link the GPU information to the CPUconst 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 trianglegl.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/

","image":"http://www.luping.net/uploads/20241022/172957574967173b45a9360.png","datePublished":"2024-11-03T02:11:06+08:00","dateModified":"2024-11-03T02:11:06+08:00","author":{"@type":"Person","name":"luping.net","url":"https://www.luping.net/articlelist/0_1.html"}}
”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 分解 WebGL 三角形设置

分解 WebGL 三角形设置

发布于2024-11-03
浏览:827

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

  1. Create a folder called “RenderTriangle”
  2. In that folder create an index.html and main.js file

Within the index.html file add the following code:

index.js





Document






  1. is the entry point for rendering the WebGL context

  2. We set up the basic HTML code and link the main.js file.

  3. 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");
  1. Get the HTML canvas by id and store it in a variable called “canvas” (you can use any name).

  2. 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.

  3. 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.

  1. gl.DEPTH_BUFFER_BIT — indicates buffers for pixel depth information

  2. 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:

targetgl.ARRAY_BUFFER
datanew 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.

Breaking Down the WebGL Triangle Setup

  • 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/

版本声明 本文转载于:https://dev.to/digitalanthro/breaking-down-the-webgl-triangle-setup-3c1m?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • PHP与C++函数重载处理的区别
    PHP与C++函数重载处理的区别
    作为经验丰富的C开发人员脱离谜题,您可能会遇到功能超载的概念。这个概念虽然在C中普遍,但在PHP中构成了独特的挑战。让我们深入研究PHP功能过载的复杂性,并探索其提供的可能性。在PHP中理解php的方法在PHP中,函数超载的概念(如C等语言)不存在。函数签名仅由其名称定义,而与他们的参数列表无关。...
    编程 发布于2025-04-30
  • 为什么我会收到MySQL错误#1089:错误的前缀密钥?
    为什么我会收到MySQL错误#1089:错误的前缀密钥?
    mySQL错误#1089:错误的前缀键错误descript [#1089-不正确的前缀键在尝试在表中创建一个prefix键时会出现。前缀键旨在索引字符串列的特定前缀长度长度,可以更快地搜索这些前缀。了解prefix keys `这将在整个Movie_ID列上创建标准主键。主密钥对于唯一识别...
    编程 发布于2025-04-30
  • 在程序退出之前,我需要在C ++中明确删除堆的堆分配吗?
    在程序退出之前,我需要在C ++中明确删除堆的堆分配吗?
    在C中的显式删除 在C中的动态内存分配时,开发人员通常会想知道是否需要手动调用“ delete”操作员在heap-exprogal exit exit上。本文深入研究了这个主题。 在C主函数中,使用了动态分配变量(HEAP内存)的指针。当应用程序退出时,此内存是否会自动发布?通常,是。但是,即使在这...
    编程 发布于2025-04-30
  • 为什么不````''{margin:0; }`始终删除CSS中的最高边距?
    为什么不````''{margin:0; }`始终删除CSS中的最高边距?
    在CSS 问题:不正确的代码: 全球范围将所有余量重置为零,如提供的代码所建议的,可能会导致意外的副作用。解决特定的保证金问题是更建议的。 例如,在提供的示例中,将以下代码添加到CSS中,将解决余量问题: body H1 { 保证金顶:-40px; } 此方法更精确,避免了由全局保证金重置引...
    编程 发布于2025-04-30
  • C++20 Consteval函数中模板参数能否依赖于函数参数?
    C++20 Consteval函数中模板参数能否依赖于函数参数?
    [ consteval函数和模板参数依赖于函数参数在C 17中,模板参数不能依赖一个函数参数,因为编译器仍然需要对非contexexpr futcoriations contim at contexpr function进行评估。 compile time。 C 20引入恒定函数,必须在编译时进行...
    编程 发布于2025-04-30
  • 如何同步迭代并从PHP中的两个等级阵列打印值?
    如何同步迭代并从PHP中的两个等级阵列打印值?
    同步的迭代和打印值来自相同大小的两个数组使用两个数组相等大小的selectbox时,一个包含country代码的数组,另一个包含乡村代码,另一个包含其相应名称的数组,可能会因不当提供了exply for for for the uncore for the forsion for for ytry...
    编程 发布于2025-04-30
  • 如何将来自三个MySQL表的数据组合到新表中?
    如何将来自三个MySQL表的数据组合到新表中?
    mysql:从三个表和列的新表创建新表 答案:为了实现这一目标,您可以利用一个3-way Join。 选择p。*,d.content作为年龄 来自人为p的人 加入d.person_id = p.id上的d的详细信息 加入T.Id = d.detail_id的分类法 其中t.taxonomy =...
    编程 发布于2025-04-30
  • 如何使用FormData()处理多个文件上传?
    如何使用FormData()处理多个文件上传?
    )处理多个文件输入时,通常需要处理多个文件上传时,通常是必要的。 The fd.append("fileToUpload[]", files[x]); method can be used for this purpose, allowing you to send multi...
    编程 发布于2025-04-30
  • Java字符串非空且非null的有效检查方法
    Java字符串非空且非null的有效检查方法
    检查字符串是否不是null而不是空的if (str != null && !str.isEmpty())Option 2: str.length() == 0For Java versions prior to 1.6, str.length() == 0 can be二手: if(str!= n...
    编程 发布于2025-04-30
  • 使用Bootstrap创建自定义文件上传按钮的技巧
    使用Bootstrap创建自定义文件上传按钮的技巧
    使用bootstrap 对于Bootstrap 3、4和5,可以简单地使用HTML解决方案: 浏览 此隐藏的输入元素将在维护自定义按钮样式的同时作为常规文件输入控件。 如果需要与IE8和下面的兼容,请使用IE8和下面,组合: { 位置:绝对; 顶部:0; 右:...
    编程 发布于2025-04-30
  • 大批
    大批
    [2 数组是对象,因此它们在JS中也具有方法。 切片(开始):在新数组中提取部分数组,而无需突变原始数组。 令ARR = ['a','b','c','d','e']; // USECASE:提取直到索引作...
    编程 发布于2025-04-30
  • 如何有效地选择熊猫数据框中的列?
    如何有效地选择熊猫数据框中的列?
    在处理数据操作任务时,在Pandas DataFrames 中选择列时,选择特定列的必要条件是必要的。在Pandas中,选择列的各种选项。选项1:使用列名 如果已知列索引,请使用ILOC函数选择它们。请注意,python索引基于零。 df1 = df.iloc [:,0:2]#使用索引0和1 的 ...
    编程 发布于2025-04-30
  • 为什么在我的Linux服务器上安装Archive_Zip后,我找不到“ class \” class \'ziparchive \'错误?
    为什么在我的Linux服务器上安装Archive_Zip后,我找不到“ class \” class \'ziparchive \'错误?
    Class 'ZipArchive' Not Found Error While Installing Archive_Zip on Linux ServerSymptom:When attempting to run a script that utilizes the ZipAr...
    编程 发布于2025-04-30
  • C++中何时选择大括号初始化?
    C++中何时选择大括号初始化?
    brace-initioner:在C 11中确定其最佳用法介绍提供各种选项的各种选项》中为变量提供了各种选项。 This flexibility can lead to confusion and uncertainty about the most appropriate initializa...
    编程 发布于2025-04-30
  • 如何使用Python的请求和假用户代理绕过网站块?
    如何使用Python的请求和假用户代理绕过网站块?
    如何使用Python的请求模拟浏览器行为,以及伪造的用户代理提供了一个用户 - 代理标头一个有效方法是提供有效的用户式header,以提供有效的用户 - 设置,该标题可以通过browser和Acterner Systems the equestersystermery和操作系统。通过模仿像Chro...
    编程 发布于2025-04-30

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3