<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Draw quad with texture</title>
</head>
<body onload="main()">
<canvas id="webgl" width="400" height="400">
Please use a browser that supports "canvas"
</canvas>
<script src="../lib/webgl-utils.js"></script>
<script src="../lib/webgl-debug.js"></script>
<script src="../lib/cuon-utils.js"></script>
<script src="../lib/cuon-matrix.js"></script>
<script>
function main(){
var canvas=document.getElementById('webgl');
var gl=getWebGLContext(canvas);
var VSHADER_SOURCE='attribute vec4 position;'+
'attribute vec2 a_TexCoord;'+
'varying vec2 v_TexCoord;'+
'void main(){gl_Position=position;'+
'v_TexCoord=a_TexCoord;}'
//sampler2D是一种与纹理有关的数据类型,texture2D是webgl内置函数
var FSHADER_SOURCE='precision mediump float;'+
'uniform sampler2D u_Sampler;'+
'varying vec2 v_TexCoord;'+
'void main(){gl_FragColor=texture2D(u_Sampler,v_TexCoord);}'
initShaders(gl,VSHADER_SOURCE,FSHADER_SOURCE);
var position=gl.getAttribLocation(gl.program,'position');
var data=new Float32Array([
-0.5,0.5,0.0,1.0,
0.5,0.5,1.0,1.0,
-0.5,-0.5,0.0,0.0,
0.5,-0.5,1.0,0.0
])
//获取数组元素的字节数
var FSIZE=data.BYTES_PER_ELEMENT;
//创建缓冲区对象
var buffer=gl.createBuffer();
//绑定缓冲区对象
gl.bindBuffer(gl.ARRAY_BUFFER,buffer);
gl.bufferData(gl.ARRAY_BUFFER,data,gl.STATIC_DRAW);
gl.vertexAttribPointer(position,2,gl.FLOAT,false,FSIZE*4,0);
gl.enableVertexAttribArray(position);
var a_TexCoord=gl.getAttribLocation(gl.program,'a_TexCoord');
gl.vertexAttribPointer(a_TexCoord,2,gl.FLOAT,false,FSIZE*4,FSIZE*2);
gl.enableVertexAttribArray(a_TexCoord)
var image=new Image();
image.onload=function(){
//创建纹理对象
var texture=gl.createTexture();
var sampler=gl.getUniformLocation(gl.program,'u_Sampler');
//对纹理的y轴进行旋转,因为图片的方向和webgl的y轴是相反的,第一个参数可以是gl.UNPACK_FLIP_Y_WEBGL,
//还有一种是gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL(颜色值的每个分量*A),第二个参数默认是false(0),取其他数字为true
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL,1);
//激活纹理单元,一般有8个纹理单元,即gl.TEXTURE0-gl.TEXTURE7
gl.activeTexture(gl.TEXTURE0);
//绑定纹理单元 第一个参数可以是gl.TEXTURE_2D或者gl.TEXTURE_CUBE_MAP
gl.bindTexture(gl.TEXTURE_2D,texture);
//配置纹理参数
gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.LINEAR)
gl.texImage2D(gl.TEXTURE_2D,0,gl.RGB,gl.RGB,gl.UNSIGNED_BYTE,image);
//将纹理单元传递给片元着色器
gl.uniform1i(sampler,0)
gl.clearColor(0.0,0.0,0.0,1.0)
gl.clear(gl.COLOR_BUFFER_BIT)
gl.drawArrays(gl.TRIANGLE_STRIP,0,4)
}
image.src="../resources/sky.jpg"
}
</script>
</body>
</html>