当前位置:网站首页>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);
边栏推荐
- Bye, Dachang! I'm going to the factory today
- [Lanzhou University] information sharing of postgraduate entrance examination and re examination
- 【数字IC验证快速入门】29、SystemVerilog项目实践之AHB-SRAMC(9)(AHB-SRAMC SVTB Overview)
- 【目标检测】YOLOv5跑通VOC2007数据集
- Ctfshow, information collection: web10
- Ctfshow, information collection: web13
- 一个需求温习到的所有知识,h5的表单被键盘遮挡,事件代理,事件委托
- The difference between full-time graduate students and part-time graduate students!
- Stream learning notes
- Qu'est - ce qu'une violation de données
猜你喜欢
Do you know the relationship between the most important indicators of two strong wind control and the quality of the customer base
众昂矿业:萤石继续引领新能源市场增长
Mathematical modeling -- what is mathematical modeling
Ctfshow, information collection: web2
Ctfshow, information collection: web8
Actually changed from 408 to self proposition! 211 North China Electric Power University (Beijing)
【深度学习】语义分割实验:Unet网络/MSRC2数据集
Typescript release 4.8 beta
知否|两大风控最重要指标与客群好坏的关系分析
全日制研究生和非全日制研究生的区别!
随机推荐
【兰州大学】考研初试复试资料分享
Niuke real problem programming - day20
Briefly describe the working principle of kept
[quick start of Digital IC Verification] 29. Ahb-sramc (9) (ahb-sramc svtb overview) of SystemVerilog project practice
Unity之ASE实现全屏风沙效果
What is Base64?
2. Heap sort "hard to understand sort"
Ctfshow, information collection: web1
2022全开源企业发卡网修复短网址等BUG_2022企业级多商户发卡平台源码
TypeScript 发布 4.8 beta 版本
"Baidu Cup" CTF competition 2017 February, web:include
Jacobo code coverage
Implementation of crawling web pages and saving them to MySQL using the scrapy framework
Whether runnable can be interrupted
【目标检测】YOLOv5跑通VOC2007数据集
[quick start of Digital IC Verification] 26. Ahb-sramc of SystemVerilog project practice (6) (basic points of APB protocol)
【服务器数据恢复】某品牌StorageWorks服务器raid数据恢复案例
简述keepalived工作原理
Matlab experience summary
[data mining] visual pattern mining: hog feature + cosine similarity /k-means clustering