设置纹理坐标(initVertexBuffers())
从缓冲区到 attribute 变量的流程:
// 顶点坐标
function initVertexBuffers(gl) {// 数据准备let verticesTexCoords = 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,])let n = 4// 创建缓冲区let vertexTexCoordBuffer = gl.createBuffer()if (!vertexTexCoordBuffer) {console.log('Failed to create vertexTexCoordBuffer')return -1}// 绑定缓冲区gl.bindBuffer(gl.ARRAY_BUFFER, vertexTexCoordBuffer)// 缓冲区存储数据gl.bufferData(gl.ARRAY_BUFFER, verticesTexCoords, gl.STATIC_DRAW)// 顶点坐标相关配置let FSIZE = verticesTexCoords.BYTES_PER_ELEMENT...// 纹理坐标相关配置let a_TexCoord = gl.getAttribLocation(gl.program, 'a_TexCoord')if (a_TexCoord < 0) {console.log('Failed to get the storage location of a_TexCoord')return -1}gl.vertexAttribPointer(a_TexCoord, 2, gl.FLOAT, false, FSIZE * 4, FSIZE * 2)gl.enableVertexAttribArray(a_TexCoord)...
}
配置和加载纹理(initTextures())
// 初始化纹理
function initTextures(gl, n) {// 创建纹理对象let texture = gl.createTexture()if (!texture) {console.log('Failed to create texture')return}// 获取u_Sampler(纹理图像)的存储位置let u_Sampler = gl.getUniformLocation(gl.program, 'u_Sampler')if (!u_Sampler) {console.log('Failed to get the storage loaction of u_Sampler')return}// 创建一个image对象let image = new Image()// 注册图像加载事件的响应函数image.onload = function () {loadTexture(gl, n, texture, u_Sampler, image)}// 浏览器加载图像image.src = '../image/sky.jpg'return true
}
创建对象,获取地址,配置
gl.TEXTURE0 到 gl_TEXTURE7 是管理纹理图像的 8 个纹理单元,每一个都与 gl.TEXTURE_2D 相关联,而后者就是绑定纹理时的纹理目标
删除一个纹理对象
获取着色器中 u_Sampler 变量的地址
uniform 变量 u_Sampler 常被称为取样器,在示例中,该变量被用来接收纹理图像,所以我们需要获取它的地址用于后续配置
// 获取u_Sampler(纹理图像)的存储位置let u_Sampler = gl.getUniformLocation(gl.program, 'u_Sampler')if (!u_Sampler) {console.log('Failed to get the storage loaction of u_Sampler')return}
参考:【《WebGL编程指南》读书笔记-颜色与纹理】_webgl warning: texsubimage: texture has not been i-CSDN博客