当前位置:网站首页>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);
边栏推荐
- Qu'est - ce qu'une violation de données
- Implementation of crawling web pages and saving them to MySQL using the scrapy framework
- [original] all management without assessment is nonsense!
- Ctfshow, information collection: web9
- Steps to create P8 certificate and warehousing account
- 【OBS】RTMPSockBuf_Fill, remote host closed connection.
- #HPDC智能基座人才发展峰会随笔
- Niuke real problem programming - day20
- 什么是pv和uv? pv、uv
- Gd32 F3 pin mapping problem SW interface cannot be burned
猜你喜欢
MongoD管理数据库的方法介绍
Ctfshow, information collection: web13
使用cpolar建立一个商业网站(2)
[quick start of Digital IC Verification] 25. AHB sramc of SystemVerilog project practice (5) (AHB key review, key points refining)
Steps to create P8 certificate and warehousing account
The download button and debug button in keil are grayed out
[server data recovery] a case of RAID data recovery of a brand StorageWorks server
Qu'est - ce qu'une violation de données
【深度学习】图像超分实验:SRCNN/FSRCNN
Introduction of mongod management database method
随机推荐
什么是数据泄露
银行需要搭建智能客服模块的中台能力,驱动全场景智能客服务升级
Oracle control file loss recovery archive mode method
摘抄的只言片语
【服务器数据恢复】某品牌StorageWorks服务器raid数据恢复案例
2.Golang基础知识
Win10 or win11 taskbar, automatically hidden and transparent
大表delete删数据导致数据库异常解决
leetcode 241. Different ways to add parentheses design priority for operational expressions (medium)
简述keepalived工作原理
jacoco代码覆盖率
[机缘参悟-40]:方向、规则、选择、努力、公平、认知、能力、行动,读3GPP 6G白皮书的五层感悟
[quick start of Digital IC Verification] 25. AHB sramc of SystemVerilog project practice (5) (AHB key review, key points refining)
MongoD管理数据库的方法介绍
There is a cow, which gives birth to a heifer at the beginning of each year. Each heifer has a heifer at the beginning of each year since the fourth year. Please program how many cows are there in the
leetcode 241. Different Ways to Add Parentheses 为运算表达式设计优先级(中等)
[Lanzhou University] information sharing of postgraduate entrance examination and re examination
What is Base64?
【搞船日记】【Shapr3D的STL格式转Gcode】
Window环境下配置Mongodb数据库