当前位置:网站首页>Webgl texture
Webgl texture
2022-07-07 15:39:00 【Vegetable chicken on the road】
design sketch :
Operation steps :
1. establish HTML5 canvas
2. Get canvas canvas Of ID
3. obtain WebGL
4. Compiling shaders , The merger process
// Vertex shader program
var VSHADER_SOURCE =
"attribute vec4 a_Position;" +
"attribute vec2 a_TextCoord;" + // Accept texture coordinates
"varying vec2 v_TexCoord;" + // Transfer texture coordinates
"void main() {" +
// Set coordinates
"gl_Position = a_Position; " + // Set coordinates
// Set texture element
"v_TexCoord = a_TextCoord; " + // Set texture coordinates
"} ";
// Chip shader
var FSHADER_SOURCE =
"precision mediump float;" + // Floating point precision needs to be declared , Otherwise, the report will be wrong No precision specified for (float)
"uniform sampler2D u_Sampler;" + // Sampler
"varying vec2 v_TexCoord;" + // Accept texture coordinates
"void main() {" +
// Set the color
"gl_FragColor = texture2D(u_Sampler, v_TexCoord);" + // Set the color
"}";
explain : Assign texture coordinates to each vertex in the vertex shader , Then extract the texture color from the texture image according to the texture coordinates of each slice in the slice shader
5. Use a buffer object to transfer multiple vertex data to vertices
function initBuffers(gl, shaderProgram) {
// Vertex coordinates and colors
var vertices = new Float32Array([
-0.5, 0.5, 0.0, 1.0,
-0.5, -0.5, 0.0, 0.0,
0.5, 0.5, 1.0, 1.0,
0.5, -0.5, 1.0, 0.0
]);
var n = 4;// Number of points
// Create buffer object
var vertexBuffer = gl.createBuffer();
// Bind the buffer object to the target
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer);
// Write data to buffer
gl.bufferData(gl.ARRAY_BUFFER,vertices,gl.STATIC_DRAW);
var FSIZE = vertices.BYTES_PER_ELEMENT;
// Get coordinate points
var a_Position = gl.getAttribLocation(shaderProgram, "a_Position");
// Allocate buffer objects to a_Position Variable
gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, FSIZE*4, 0);
// Connect a_Position Variable and the buffer object assigned to it
gl.enableVertexAttribArray(a_Position);
// obtain Color Coordinates
var a_TextCoord = gl.getAttribLocation(shaderProgram, "a_TextCoord");
// Allocate buffer objects to a_Position Variable
gl.vertexAttribPointer(a_TextCoord, 2, gl.FLOAT, false, FSIZE*4, FSIZE*2);
// Connect a_Position Variable and the buffer object assigned to it
gl.enableVertexAttribArray(a_TextCoord);
return n;
}
6. Create texture , Load texture image , Configuration properties , stay webgl Use it in ;
function initTexture(gl, shaderProgram, n){
// Create texture objects
var texture = gl.createTexture();
// obtain u_Sampler Storage location
var u_Sampler = gl.getUniformLocation(shaderProgram, 'u_Sampler');
// establish image object
var image = new Image();
// Load texture
image.onload = function(){ loadTexture(gl, n, texture, u_Sampler, image); };
// The browser starts loading pictures Be careful : It must be 2^mx2^n Size pictures
image.src = "../TexturedQuad/shan.jpg";
return true;
}
u_Sampler Represents getting texture color from texture image
gl.createTexture(); Create texture objects to store texture objects ;gl.TEXTURE0~gl.TEXTURE7 Manage texture images 8 Texture units
Be careful ( Image loading solution ):
1). If Google browser is loaded locally when the image is loaded here, an error may be reported , The specific solution is Baidu , I don't know how to set it anyway .
2). The picture is obtained from the server , There will be no unsolicited problem
3). I prefer this way , Turn your local pictures into base64 The style of , And then the picture src Just use the turned address to solve it perfectly
7. Load texture image , Configuration properties , stay webgl Use it in ;
function loadTexture(gl, n, texture, u_Sampler,image){
//1. On the texture image Y Axis reversal
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
//2. Turn on 0 Texture unit no
gl.activeTexture(gl.TEXTURE0);
//3. towards target Bind texture object
gl.bindTexture(gl.TEXTURE_2D, texture);
//4. Configure texture parameters
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
//5. Configure texture image
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
//6. take 0 No. texture image passed to shader
gl.uniform1i(u_Sampler, 0);
// Empty <canvas>
gl.clear(gl.COLOR_BUFFER_BIT);
// Draw a rectangle
gl.drawArrays(gl.TRIANGLE_STRIP, 0, n);
}
(1) On the texture image Y Axis reversal , because WebGL Texture coordinate system t Axis ( It is divided into t Axis and s Axis ) The direction and coordinate system of the picture Y Opposite axis direction . So it will Y Reverse the axis .
gl.pixelStorei: The first parameter : There are two , One UNPACK_FLIP_Y_WEBGL Represents right Y Axis reversal , The default is false; One UNPACK_PREMULTIPLY_ALPHA_WEBGL Represents the image RGB Color is worth multiplying each component by A, The default value is false;
(2) Turn on 0 Texture unit no
WebGL Use multiple textures at the same time through the mechanism of texture units ,gl.TEXTURE0~gl.TEXTURE7 Manage texture images 8 Texture units
(3) Bind texture object
gl.bindTexture Two parameters
The first parameter : There are two choices TEXTURE_2D Represents two-dimensional texture ,TEXTURE_CUBE_MAP Cubic texture ;
The second parameter : Represents the bound texture unit
(4) Configure texture parameters
gl.texParameteri Three parameters
The first parameter : There are two choices TEXTURE_2D Represents two-dimensional texture ,TEXTURE_CUBE_MAP Cubic texture ;
The second parameter : Yes 4 Texture parameters
1.TEXTURE_MAX_FILTER: Amplification method Default :gl.LINEAR
2.TEXTURE_MIN_FILTER: How to shrink Default :gl.NEAREST_MIPMAP_LINEAR
3.TEXTURE_WRAP_S: Horizontal filling method Default :gl.REPEAT
4.TEXTURE_WRAP_T: Vertical filling method Default :gl.REPEAT
The third parameter :
gl.LINEAR: Use the weighted values of the four pixels closest to the center of the new pixel to average ( Good picture quality , But it's expensive )
gl.NEAREST_MIPMAP_LINEAR: Use the color value of the pixel closest to the center of the mapped pixel on the original texture as the value of the new pixel
gl.REPEAT: Tile repeat texture
gl.REPEAT: Mirror symmetrical repeating texture
gl.REPEAT: Use texture image edge values
(5) Configure texture image
gl.texImage2D There are six parameters
The first parameter : There are two choices TEXTURE_2D Represents two-dimensional texture ,TEXTURE_CUBE_MAP Cubic texture ;
The second parameter : The default is 0, When it comes to three dimensions
The third parameter : The internal format of the image Yes :gl.RGB( Red, green and blue )、gl.RGBA( Red green blue transparency )、gl.ALPHA(0.0,0.0,0.0, transparency )、gl.LUMINANCE(L、L、L、1L: Lumen )、 gl.LUMINANCE_ALPHA(L、L、L, transparency )
Lumen : Indicates the brightness of the object surface we perceive , Equal to the weighted average of the red, green and blue color component values to calculate lumens
Fourth parameter : Texture data format , Must be the same as the third parameter
Fifth parameter : Texture data format UNSIGNED_BYTE: Represents an unsigned integer , Each color component occupies 1 byte
UNSIGNED_SHORT_5_6_5: Express RGB, Each component occupies 5,6,5 The bit
UNSIGNED_SHORT_4_4_4_4: Express RGBA, Each component occupies 4,4,4,4 The bit
UNSIGNED_SHORT_5_5_5_1: Express RGBA, Each component occupies 5 The bit ,A Components occupy 1 The bit
Sixth parameter : Texture image image object
(6) take 0 No. texture image passed to shader
uniform1i(u_Sampler, 0); Slice shaders here and above "gl_FragColor = texture2D(u_Sampler, v_TexCoord);" + // Set the color , There's a connection
among :sampler2D Bound to the gl.TEXTURE_2D On ,samplerCube Bound to the gl.TEXTURE_CUBE_MAP On
explain : Maybe you followed the code and found , Where's my picture , Why not show ? This is a webgl This is a place with holes , Because I don't know when the big guys will package the imported libraries , So the image texture has not been processed .
Actually , Here are two solutions :
1. The size of the picture is 2 Idempotent size of , Such as 256*256;
(2 The power of is because rasterization requires fast value taking of texture samples , All incoming surfaces are thus agreed (Surface) Must be 2 The power of . The current practice is generally the driver layer ( Or engine layer ) Did a texture filter to put non 2 The texture of power is stretched or compressed to 2 The power of is passed into ( such as Mipmap Hierarchy ), This implementation allows arbitrary textures to be imported . But based on this principle, it is not 2 Power will cause non proportional deformation of texture , Therefore, for most cases where pixel alignment is strictly required, it is still necessary for art to customize images according to this rule )
2. When configuring texture parameters , add s,t Configuration of .
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
边栏推荐
- [markdown grammar advanced] make your blog more exciting (IV: set font style and color comparison table)
- 最安全的证券交易app都有哪些
- leetcode 241. Different ways to add parentheses design priority for operational expressions (medium)
- 【服务器数据恢复】戴尔某型号服务器raid故障的数据恢复案例
- [follow Jiangke University STM32] stm32f103c8t6_ PWM controlled DC motor_ code
- 【数字IC验证快速入门】20、SystemVerilog学习之基本语法7(覆盖率驱动...内含实践练习)
- Do not use memset to clear floating-point numbers
- 【数字IC验证快速入门】19、SystemVerilog学习之基本语法6(线程内部通信...内含实践练习)
- Database exception resolution caused by large table delete data deletion
- The difference between full-time graduate students and part-time graduate students!
猜你喜欢
【数字IC验证快速入门】29、SystemVerilog项目实践之AHB-SRAMC(9)(AHB-SRAMC SVTB Overview)
Bye, Dachang! I'm going to the factory today
Use cpolar to build a business website (2)
[Lanzhou University] information sharing of postgraduate entrance examination and re examination
Briefly describe the working principle of kept
With 8 modules and 40 thinking models, you can break the shackles of thinking and meet the thinking needs of different stages and scenes of your work. Collect it quickly and learn it slowly
[quick start of Digital IC Verification] 25. AHB sramc of SystemVerilog project practice (5) (AHB key review, key points refining)
Guangzhou Development Zone enables geographical indication products to help rural revitalization
[make a boat diary] [shapr3d STL format to gcode]
Summer safety is very important! Emergency safety education enters kindergarten
随机推荐
什么是pv和uv? pv、uv
[quickstart to Digital IC Validation] 20. Basic syntax for system verilog Learning 7 (Coverage Driven... Including practical exercises)
Unity之ASE实现卡通火焰
【原创】一切不谈考核的管理都是扯淡!
HPDC smart base Talent Development Summit essay
[make a boat diary] [shapr3d STL format to gcode]
【Markdown语法高级】让你的博客更精彩(四:设置字体样式以及颜色对照表)
【数字IC验证快速入门】18、SystemVerilog学习之基本语法5(并发线程...内含实践练习)
2022全开源企业发卡网修复短网址等BUG_2022企业级多商户发卡平台源码
使用cpolar建立一个商业网站(2)
Unity之ASE实现全屏风沙效果
Do you know the relationship between the most important indicators of two strong wind control and the quality of the customer base
[follow Jiangke University STM32] stm32f103c8t6_ PWM controlled DC motor_ code
银行需要搭建智能客服模块的中台能力,驱动全场景智能客服务升级
【OBS】RTMPSockBuf_Fill, remote host closed connection.
TypeScript 发布 4.8 beta 版本
#HPDC智能基座人才发展峰会随笔
Unity's ASE realizes cartoon flame
【数字IC验证快速入门】19、SystemVerilog学习之基本语法6(线程内部通信...内含实践练习)
Super signature principle (fully automated super signature) [Yun Xiaoduo]