5. 用键盘控制三角形的旋转
本章学习一个简单交互:用键盘的左右键控制三角形向左或向右旋转。
WebGL本身并没有输入相关的API,我们需要借助于浏览器的力量。
我使用HTML文档对象的onkeydown和onkeyup事件。在事件处理函数中,我首先判断被按下或弹起的键是否是左或右,如果是,就设置相应键的状态为按下或弹起。我把左或右这两个按键的状态分开保存,而不是用一个统一的标记值标记它们。这允许我们处理左右键被同时按下的情况(虽然目前看起来有点没有必要,但以后会用得到)。
注意,我使用的事件处理函数用document.onkeydown = function(e)这种格式定义。如果你用的不是FF浏览器,该函数可能不会正确执行,请自行修改。
在某个按键被按下的情况下,三角形就不停地向左或向右旋转,直到该按键被松开。
我仍然用一个js变量来记录当前三角形要旋转的角度;左转角度加10,右转角度减10。
整合的源码如下:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=gb2312">
<script type="text/javascript" src="glMatrix-0.9.5.js"></script>
<script id="shader-vs" type="x-shader/x-vertex">
attribute vec3 v3Position;
uniform mat4 um4Rotate;
varying vec2 v_texCoord;
void main(void)
{
//vec4 v4pos = um4Rotate * vec4(v3Position, 1.0);
//v_texCoord = vec2((v4pos.x+1.0)/2.0, 1.0-(v4pos.y+1.0)/2.0);
//gl_Position = v4pos;
v_texCoord = vec2((v3Position.x+1.0)/2.0, 1.0-(v3Position.y+1.0)/2.0);
gl_Position = um4Rotate * vec4(v3Position, 1.0);
}
</script>
<script id="shader-fs" type="x-shader/x-fragment">
#ifdef GL_FRAGMENT_PRECISION_HIGH
precision highp float;
#else
precision mediump float;
#endif
uniform sampler2D s_texture;
varying vec2 v_texCoord;
void main(void)
{
gl_FragColor = texture2D(s_texture, v_texCoord);
}
</script>
<script>
function ShaderSourceFromScript(scriptID)
{
var shaderScript = document.getElementById(scriptID);
if (shaderScript == null) return "";
var sourceCode = "";
var child = shaderScript.firstChild;
while (child)
{
if (child.nodeType == child.TEXT_NODE ) sourceCode += child.textContent;
child = child.nextSibling;
}
return sourceCode;
}
var webgl = null;
var vertexShaderObject = null;
var fragmentShaderObject = null;
var programObject = null;
var triangleBuffer = null;
var v3PositionIndex = 0;
var textureObject = null;
var samplerIndex = -1;
var interval = 300;
var angle = 0;
var um4RotateIndex = -1;
var leftKeyDown = false;
var rightKeyDown = false;
function LoadData()
{
var jsArrayData = [
0.0, 0.5, 0.0,//上顶点
-0.5, -0.5, 0.0,//左顶点
0.5, 0.0, 0.0];//右顶点
triangleBuffer = webgl.createBuffer();
webgl.bindBuffer(webgl.ARRAY_BUFFER, triangleBuffer);
webgl.bufferData(webgl.ARRAY_BUFFER, new Float32Array(jsArrayData), webgl.STATIC_DRAW);
textureObject = webgl.createTexture();
webgl.bindTexture(webgl.TEXTURE_2D, textureObject);
var img = document.getElementById('myTexture');
webgl.texImage2D(webgl.TEXTURE_2D, 0, webgl.RGB, webgl.RGB, webgl.UNSIGNED_BYTE, img);
return 0;
}
function RenderScene()
{
webgl.clearColor(0.0, 0.0, 0.0, 1.0);
webgl.clear(webgl.COLOR_BUFFER_BIT);
webgl.bindBuffer(webgl.ARRAY_BUFFER, triangleBuffer);
webgl.enableVertexAttribArray(v3PositionIndex);
webgl.vertexAttribPointer(v3PositionIndex, 3, webgl.FLOAT, false, 0, 0);
webgl.texParameteri(webgl.TEXTURE_2D, webgl.TEXTURE_MIN_FILTER, webgl.NEAREST);
webgl.texParameteri(webgl.TEXTURE_2D, webgl.TEXTURE_MAG_FILTER, webgl.NEAREST);
webgl.texParameteri(webgl.TEXTURE_2D, webgl.TEXTURE_WRAP_S, webgl.CLAMP_TO_EDGE);
webgl.texParameteri(webgl.TEXTURE_2D, webgl.TEXTURE_WRAP_T, webgl.CLAMP_TO_EDGE);
webgl.activeTexture(webgl.TEXTURE0);
webgl.bindTexture(webgl.TEXTURE_2D, textureObject);
webgl.uniform1i(samplerIndex, 0);
var m4Rotate = mat4.create();
mat4.identity(m4Rotate);
mat4.rotateZ(m4Rotate, angle*Math.PI/180);
webgl.uniformMatrix4fv(um4RotateIndex, false, m4Rotate);
webgl.drawArrays(webgl.TRIANGLES, 0, 3);
}
function RotateTriangle()
{
if(leftKeyDown) angle += 10;
if(rightKeyDown) angle -= 10;
if(angle >= 360) angle -= 360;
if(angle < 0) angle += 360;
RenderScene();
}
document.onkeydown = function(e)
{
if(e.keyCode == 37) leftKeyDown = true;
if(e.keyCode == 39) rightKeyDown = true;
}
document.onkeyup = function(e)
{
if(e.keyCode == 37) leftKeyDown = false;
if(e.keyCode == 39) rightKeyDown = false;
}
function Init()
{
var myCanvasObject = document.getElementById('myCanvas');
webgl = myCanvasObject.getContext("experimental-webgl");
webgl.viewport(0, 0, myCanvasObject.clientWidth, myCanvasObject.clientHeight);
vertexShaderObject = webgl.createShader(webgl.VERTEX_SHADER);
fragmentShaderObject = webgl.createShader(webgl.FRAGMENT_SHADER);
webgl.shaderSource(vertexShaderObject, ShaderSourceFromScript("shader-vs"));
webgl.shaderSource(fragmentShaderObject, ShaderSourceFromScript("shader-fs"));
webgl.compileShader(vertexShaderObject);
webgl.compileShader(fragmentShaderObject);
if(!webgl.getShaderParameter(vertexShaderObject, webgl.COMPILE_STATUS)){alert(webgl.getShaderInfoLog(vertexShaderObject));return;}
if(!webgl.getShaderParameter(fragmentShaderObject, webgl.COMPILE_STATUS)){alert(webgl.getShaderInfoLog(fragmentShaderObject));return;}
programObject = webgl.createProgram();
webgl.attachShader(programObject, vertexShaderObject);
webgl.attachShader(programObject, fragmentShaderObject);
webgl.bindAttribLocation(programObject, v3PositionIndex, "v3Position");
webgl.linkProgram(programObject);
if(!webgl.getProgramParameter(programObject, webgl.LINK_STATUS)){alert(webgl.getProgramInfoLog(programObject));return;}
samplerIndex = webgl.getUniformLocation(programObject, "s_texture");
um4RotateIndex = webgl.getUniformLocation(programObject, "um4Rotate");
webgl.useProgram(programObject);
if(LoadData() != 0){alert("error:LoadData()!");return;}
window.setInterval("RotateTriangle()", interval);
}
</script>
</head>
<body onload='Init()'>
<canvas id="myCanvas" style="border:1px solid red;" width='600px' height='450px'></canvas>
<img id="myTexture" src='texture.bmp'>
</body>
</html>