WebGL3D overview of HTML5 (I)-WebGL native development opens the new era of Web 3D rendering _ html5 tutorial skills-

Source: Internet
Author: User
WebGL has ushered in a new era of 3D rendering of web pages. It allows direct 3D Content Rendering in the canvas without using any plug-ins. Do you feel particularly surprised to see it here, webGL has a good Chinese tutorial, that is, the first link in the reference below, so I will not make a shift here. The content below is just a brief summary of what I learned, interested friends can use WebGL to usher in a new era of 3D rendering of web pages. It allows direct 3D Content Rendering in the canvas without any plug-ins. Like the canvas 2D API, WebGL uses scripts to manipulate objects. Therefore, the steps are similar: prepare the work context, prepare data, and draw and render objects in the canvas. What is different from 2D is that 3D involves more knowledge, such as world, light, texture, camera, matrix, and other professional knowledge. WebGL has a good Chinese tutorial, that is, the first link in the following reference, so I will not make an axe to the class here. The following content is just a brief summary of the learning content.

Browser support
Microsoft has its own graphic development plan and does not support WebGL. Therefore, in addition to installing plug-ins, IE cannot run WebGL. Other mainstream browsers, such as Chrome, FireFox, Safari, and Opera, can be installed with the latest version. In addition to the latest installation in the browser, you must also ensure that the driver of the video card is also the latest.
After these settings are installed, 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 properly installed, you still cannot run WebGL. You can enable WebGL to support a try. The method for enabling is as follows:
Chrome
We need to add some startup parameters for Chrome. The following procedure takes the Windows operating system as an example: Find the Chrome browser's official style, click the official style on the right, select the official style in the target box, and add the following content after the quotation marks behind chrome.exe:

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

Click OK to close Chrome, and then use this shortcut to start Chrome.
The meanings of the parameters are as follows:
-- Enable-webgl indicates enabling WebGL support;
-- Ignore-gpu-blacklist indicates that the GPU blacklist is ignored. In other words, it is not recommended to run WebGL because some GPU cards are too old. This parameter allows the browser to ignore this blacklist, forcibly run WebGL;
-- Allow-file-access-from-files indicates that resources can be loaded locally. If you are not a WebGL developer, you do not need to develop or debug WebGL. You just want to check the WebGL Demo, you do not need to add this parameter.

Firefox
For Firefox users, enter "about: config" in the address bar of the browser, press enter, and then search "webgl" in the filter. set force-enabled to true; Set webgl. set disabled to false; search for "security." In the filter. fileuri. strict_origin_policy ", set security. fileuri. set strict_origin_policy to false, close all currently enabled Firefox windows, and restart Firefox.
The first two settings are to force WebGL support and the last security. fileuri. the setting of strict_origin_policy is to allow resources to be loaded locally. If you are not a web GL developer and do not need to develop or debug WebGL, you just want to check the WebGL Demo. You can skip this setting.

Safari
Find "properties"> "advanced" in the menu, select "show development menu", go to the "Development" menu, and select "enable WebGL ".

Development procedure

The following code simply summarizes the related concepts. It comes from the reference Chinese tutorials and involves a lot of 3D knowledge. If you are interested, you can skip to the Chinese tutorial in the practical reference, which is more detailed and accurate than what I have explained here. Let's just take a look at it. You don't have to go into the meaning of each line of code.


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

The Code is as follows:




Yourbrowserdoesn 'tappeartosuppthethehtml5canvaselement.



The following is the time to officially start writing scripts. First, let's 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, 1.0 );
Gl. enable (gl. DEPTH_TEST );
DrawScene ();
}


The following methods represent the typical WebGL draw steps:

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 obtain the WebGL painting environment, you need to pass the parameter "webgl" to canvas. the getContext method is enough, but the current WebGL standard is not finalized, so the parameters used in the experiment are "experimental-webgl ". Of course, you can call canvas. getContext ("experimental-webgl") directly. After the standard is set, you can modify another code.

Step 2: Initialize the Shaders-initShaders
The Shader concept of the shadow is relatively simple. To put it bluntly, it is the graphics card operation command. A large amount of color, location, and other information calculations are required to construct a 3D scenario. If these calculations are executed by software, they will be slow. Therefore, the video card can calculate these operations at a very high speed. The coloring tool specifies how to execute these calculations. The colorant code is written in a colorant language called GLSL, which we will not talk about.
The shader can be defined in html and used in code. Of course, the same is true if you use a string in the program to define the shader.
Next, let's take a look at the definition:

The Code is as follows:



Precisionmediumpfloat;
Varyingvec4vColor;
Voidmain (void ){
Gl_FragColor = vColor;
}
Script

Attributevec3aVertexPosition;
Attributevec4aVertexColor;
Uniformmat4uMVMatrix;
Uniformmat4uPMatrix;
Varyingvec4vColor;
Voidmain (void ){
Gl_Position = uPMatrix * uMVMatrix * vec4 (aVertexPosition, 1.0 );
VColor = aVertexColor;
}
Script


There are two paintors: The surface paintors and the vertex paintors.
It is worth noting that 3D models in computers are basically described by vertices and triangles. The vertex shader processes the data of these vertices, the surface coloring tool processes the point data on the Triangle through interpolation.
The Vertex coloring tool defined above defines the vertex position and color calculation method, while the surface coloring tool defines the color Calculation Method of interpolation points. In actual application scenarios, it also involves processing effects such as light in the coloring tool.
You can find the coloring ERs in the program and use them:

The Code is as follows:


VarshaderProgram;
FunctioninitShaders (){
VarfragmentShader = getShader (gl, "shader-fs ");
VarvertexShader = getShader (gl, "shader-");
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 ");
}


The coloring tool is available, but how can we execute the video card? The Program is the bridge. It is the native binary code of WebGL, the function is basically to let the video card run the shader code to render the specified model data.
Here we also use an auxiliary method getShader, which is to traverse the html document, find the definition of the colorant, and create the colorant after obtaining the definition. I will not go into detail 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 ("anerroccurredcompilingtheshaders:" + gl. getShaderInfoLog (shader ));
Returnnull;
}
Returnshader;
}


Step 3: Create/load model data-initBuffers
In these small examples, model data is basically directly generated. In actual programs, 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,-1.0, 0.0,
1.0,-1.0, 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 color data of triangle vertices and puts them in the buffer zone.

Step 4: render-drawScene
After the data is ready, you can submit it to WebGL for rendering. The gl. drawArrays method is called here. Check the Code:

The Code is as follows:


FunctiondrawScene (){
Gl. viewport (0, 0, gl. viewportWidth, gl. viewportHeight );
Gl. clear (gl. COLOR_BUFFER_BIT | gl. DEPTH_BUFFER_BIT );
PMatrix = okMat4Proj (45.0, gl. viewportWidth/gl. viewportHeight, 0.1, 100.0 );
MvMatrix = okMat4Trans (-1.5, 0.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 based on the vertex and color data in the buffer. There are also some auxiliary methods for generating the projection matrix and the rectangle of the Model View (using the matrix auxiliary method in the oak 3D graphics library) that have little to do with the topic. I will not explain it in detail here.
Basically, the process is so much. More complex textures and light are implemented by adding some WegGL features. For more information, see the Chinese tutorial later, detailed examples are provided.

How is it? What is the feeling of using native WebGL for development? Not only do you need deep 3D knowledge, but you also need to know various implementation details. WebGL is used to adapt to various application scenarios flexibly. However, for a majority of non-professionals like me, many details are not required. This gave birth to a variety of class libraries for auxiliary development, such as the Oak3D library used in this section (in order to demonstrate WebGL development, the example only uses the matrix auxiliary method ). The next section describes a large number of Three. js graphics libraries.

Practical reference:
Http://www.hiwebgl.com /? P = 42

Development Center: https://developer.mozilla.org/en/WebGL

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.