Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the process of opening 3D rendering of web pages by WebGL native development in HTML5?

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail the process of opening web page 3D rendering in the native development of WebGL in HTML5. The content of the article is of high quality, so the editor will share it with you for reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.

WebGL ushered in a new era of web 3D rendering, allowing 3D content to be rendered directly in canvas without any plug-ins. WebGL, like API in canvas 2D, manipulates objects through scripts, so the steps are basically similar: prepare the work context, prepare the data, draw objects in canvas and render. Unlike 2D, 3D involves more knowledge, such as world, light, texture, camera, matrix, and so on.

Browser support

Because Microsoft has its own graphics development plan, it does not support WebGL, so IE is currently unable to run WebGL except to install plug-ins. Other major browsers, such as Chrome, FireFox, Safari, Opera, etc., are all equipped with the latest version. In addition to the browser to install the latest, but also to ensure that the driver of the graphics card is also up-to-date.

After installing these, you can open the browser and enter the following URL to verify the browser's support for WebGL: http://webglreport.sourceforge.net/.

After the above browsers are normally installed, you still can't run WebGL, so you can force WebGL support to try. The opening method is as follows:

Chrome browser

We need to add some startup parameters for Chrome. Take the Windows operating system as an example: find the shortcut to the Chrome browser, right-click the shortcut, and select the attribute. In the target box, after the quotation marks after the chrome.exe, add the following:

-- enable-webgl--ignore-gpu-blacklist--allow-file-access-from-files

Click OK to close Chrome, and then use this shortcut to launch the Chrome browser.

Several parameters have the following meanings:

-- enable-webgl means to enable WebGL support

-- ignore-gpu-blacklist means ignoring the GPU blacklist, that is, some graphics cards, GPU, are not recommended to run WebGL because they are too old. This parameter allows browsers to ignore the blacklist and force WebGL to run.

-- allow-file-access-from-files means allowing resources to be loaded locally. If you are not a WebGL developer and do not need to develop and debug WebGL, you just want to take a look at WebGL's Demo, then you do not need to add this parameter.

Firefox browser

Firefox users please enter "about:config" in the browser's address bar, enter, then search for "webgl" in the filter (filter), set webgl.force-enabled to true;, set webgl.disabled to false; to search for "security.fileuri.strict_origin_policy" in the filter (filter), set security.fileuri.strict_origin_policy to false;, then close all currently open Firefox windows and restart Firefox.

The first two settings are to enable WebGL support, and the last security.fileuri.strict_origin_policy setting is to allow resources to be loaded locally. If you are not a WebGL developer and do not need to develop and debug WebGL, you just want to take a look at WebGL's Demo, then you can not set this item.

Safari browser

Find "Properties" → "Advanced" in the menu, select "Show Development menu", then go to the "Development" menu, and select "Open WebGL".

Development steps

The following code is just a brief summary of the relevant concepts, it comes from the Chinese tutorial in the reference, involving more 3D knowledge. Interested students can directly skip to the Chinese course in the practical reference, which is much more detailed and accurate than what I have explained here. Students who join in the fun can simply take a look at it, and there is no need to delve into the meaning of each line of code.

Preparatory work

Needless to say, add a canvas element to the page as a rendering container. For example:

The code is as follows:

Yourbrowserdoesn'tappeartosupporttheHTML5canvaselement.

Here's the time to start writing scripts, first take a look at the program entry and the overall structure:

The code is as follows:

Functionstart () {

Varcanvas=document.getElementById ("glcanvas")

InitGL (canvas)

InitShaders ()

InitBuffers ()

Gl.clearColor (0. 0. 0. 0. 0. 0. 0)

Gl.enable (gl.DEPTH_TEST)

DrawScene ()

}

The several methods here represent the typical drawing steps of WebGL:

Step 1: initialize the WebGL work environment-initGL

The code for this method is as follows:

The code is as follows:

Vargl

FunctioninitGL (canvas) {

Gl=null

Try {

/ / Trytograbthestandardcontext.Ifitfails,fallbacktoexperimental.

Gl=canvas.getContext ("webgl") | | canvas.getContext ("experimental-webgl")

}

Catch (e) {} / / Ifwedon'thaveaGLcontext,giveupnow

If (! gl) {

Alert ("UnabletoinitializeWebGL.Yourbrowsermaynotsupportit.")

}

}

This method is very simple, that is, to get the drawing environment of WebGL, you need to pass the parameter "webgl" to the canvas.getContext method, but because the current WebGL standard has not been finalized, the parameters used in the experimental phase are all "experimental-webgl". Of course, you can also directly call canvas.getContext ("experimental-webgl"). After the standard is set, you can modify one more code.

Step 2: initialize the shader Shaders-initShaders

The concept of shader Shader is relatively simple, to put it bluntly, it is the graphics card operation instruction. Constructing a 3D scene requires a lot of color, location and other information calculations, if these calculations are performed by software, the speed will be very slow. So let the graphics card to calculate these operations, the speed is very fast; how to perform these calculations is specified by the shader. The shader code is written in a shader language called GLSL, which we won't talk about.

Shaders can be defined in html and used in code. Of course, it's the same with you using a string to define the shader in the program.

Let's take a look at the definition first:

The code is as follows:

Precisionmediumpfloat

Varyingvec4vColor

Voidmain (void) {

Gl_FragColor=vColor

}

Attributevec3aVertexPosition

Attributevec4aVertexColor

Uniformmat4uMVMatrix

Uniformmat4uPMatrix

Varyingvec4vColor

Voidmain (void) {

Gl_Position=uPMatrix*uMVMatrix*vec4 (aVertexPosition,1.0)

VColor=aVertexColor

}

There are two shaders: the face shader and the vertex shader.

With regard to these two shaders, it is necessary to note that the 3D models in the computer are basically described by points combined with triangular patches, the vertex shader is to process the data of these points, and the face shader is through interpolation to process the data of the points on the triangular patch.

The vertex shader defined above defines the position and color calculation of the vertex, while the face shader defines how the color of the interpolation point is calculated. In the actual application scene, it will also involve effects such as dealing with rays in the shader.

Shaders are defined, and you can find them in the program and use them:

The code is as follows:

VarshaderProgram

FunctioninitShaders () {

VarfragmentShader=getShader (gl, "shader-fs")

VarvertexShader=getShader (gl, "shader-vs")

ShaderProgram=gl.createProgram ()

Gl.attachShader (shaderProgram,vertexShader)

Gl.attachShader (shaderProgram,fragmentShader)

Gl.linkProgram (shaderProgram)

If (! gl.getProgramParameter (shaderProgram,gl.LINK_STATUS)) {

Alert ("Couldnotinitialiseshaders")

}

Gl.useProgram (shaderProgram)

ShaderProgram.vertexPositionAttribute=gl.getAttribLocation (shaderProgram, "aVertexPosition")

Gl.enableVertexAttribArray (shaderProgram.vertexPositionAttribute)

ShaderProgram.vertexColorAttribute=gl.getAttribLocation (shaderProgram, "aVertexColor")

Gl.enableVertexAttribArray (shaderProgram.vertexColorAttribute)

ShaderProgram.pMatrixUniform=gl.getUniformLocation (shaderProgram, "uPMatrix")

ShaderProgram.mvMatrixUniform=gl.getUniformLocation (shaderProgram, "uMVMatrix")

}

There is a shader, but how to get the video card to execute, Program is such a bridge, it is the native binary code of WebGL, its function is basically to let the video card run shader code to render the specified model data.

An auxiliary method, getShader, is also used here, which is to traverse the html document, find the definition of the shader, and create the shader after getting the definition. I won't go into details here:

The code is as follows:

FunctiongetShader (gl,id) {

VarshaderScript,theSource,currentChild,shader

ShaderScript=document.getElementById (id)

If (! shaderScript) {

Returnnull

}

TheSource= ""

CurrentChild=shaderScript.firstChild

While (currentChild) {

If (currentChild.nodeType==currentChild.TEXT_NODE) {

TheSource+=currentChild.textContent

}

CurrentChild=currentChild.nextSibling

}

If (shaderScript.type== "x-shader/x-fragment") {

Shader=gl.createShader (gl.FRAGMENT_SHADER)

} elseif (shaderScript.type== "x-shader/x-vertex") {

Shader=gl.createShader (gl.VERTEX_SHADER)

} else {

/ / Unknownshadertype

Returnnull

}

Gl.shaderSource (shader,theSource)

/ / Compiletheshaderprogram

Gl.compileShader (shader)

/ / Seeifitcompiledsuccessfully

If (! gl.getShaderParameter (shader,gl.COMPILE_STATUS)) {

Alert ("Anerroroccurredcompilingtheshaders:" + gl.getShaderInfoLog (shader))

Returnnull

}

Returnshader

}

Step 3: create / load model data-initBuffers

In these small examples, the model data is basically generated directly, and in the actual program, the data should be loaded from the model:

The code is as follows:

VartriangleVertexPositionBuffer

VartriangleVertexColorBuffer

FunctioninitBuffers () {

TriangleVertexPositionBuffer=gl.createBuffer ()

Gl.bindBuffer (gl.ARRAY_BUFFER,triangleVertexPositionBuffer)

Varvertices= [

0.0,1.0,0.0

-1. 0. 010. 0. 0

1.0 mai 1.0 min 0.0

]

Gl.bufferData (gl.ARRAY_BUFFER,newFloat32Array (vertices), gl.STATIC_DRAW)

TriangleVertexPositionBuffer.itemSize=3

TriangleVertexPositionBuffer.numItems=3

TriangleVertexColorBuffer=gl.createBuffer ()

Gl.bindBuffer (gl.ARRAY_BUFFER,triangleVertexColorBuffer)

Varcolors= [

1.0,0.0,0.0,1.0

0.0,1.0,0.0,1.0

0.0,0.0,1.0,1.0

]

Gl.bufferData (gl.ARRAY_BUFFER,newFloat32Array (colors), gl.STATIC_DRAW)

TriangleVertexColorBuffer.itemSize=4

TriangleVertexColorBuffer.numItems=3

}

The above code creates the vertices of the triangle and the color data of the vertices and puts them in the buffer.

Step 4: render-drawScene

Once the data is ready, just give it to WebGL to render. Here, the gl.drawArrays method is called. Look at the code:

The code is as follows:

FunctiondrawScene () {

Gl.viewport (0pc0pl gl.viewportWidth.gl.viewportHeight)

Gl.clear (gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)

PMatrix=okMat4Proj (45.0, gl.viewportWidthback, gl.viewportHeight, 0.1100.0)

MvMatrix=okMat4Trans (- 1. 5, 0. 0, 1. 0, 7. 0)

Gl.bindBuffer (gl.ARRAY_BUFFER,triangleVertexPositionBuffer)

Gl.vertexAttribPointer (shaderProgram.vertexPositionAttribute,triangleVertexPositionBuffer.itemSize,gl.FLOAT,false,0,0)

Gl.bindBuffer (gl.ARRAY_BUFFER,triangleVertexColorBuffer)

Gl.vertexAttribPointer (shaderProgram.vertexColorAttribute,triangleVertexColorBuffer.itemSize,gl.FLOAT,false,0,0)

SetMatrixUniforms ()

Gl.drawArrays (gl.TRIANGLES,0,triangleVertexPositionBuffer.numItems)

}

This function first sets the background of the 3D world to black, then sets the projection matrix, sets the position of the object to be drawn, and then draws the object according to the vertex and color data in the buffer. There are also some auxiliary methods for generating projection matrices and model view rectangles (using the matrix auxiliary methods in the Oak3D graphics library) that have little to do with the topic, so I won't explain them in detail here.

Basically, there are so many processes, more complex textures, lighting and so on are realized by adding some WegGL features on the basis of these. Please refer to the later Chinese tutorial for detailed examples.

How's it going? What's it like to use native WebGL development? Not only need to have a deep 3D knowledge, but also need to know a variety of implementation details. WebGL does this to adapt flexibly to a variety of application scenarios, but for most non-professionals like me, there are a lot of details that you don't need to know. This leads to a variety of development-assisted class libraries, such as the Oak3D library used in this section (to demonstrate WebGL development, only matrix-assisted methods are used in the example). The next section will introduce a more commonly used Three.js graphics library.

On the HTML5 WebGL native development to open the process of web 3D rendering is shared here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report