我会持续更新关于wegl的编程指南中的代码。
当前的代码不会使用书中的缩写,每一步都是会展开写。希望能给后来学习的一些帮助
git代码地址
接着 上一节 接着做平移的转化。在本次的案例案例中主要是xy的坐标变量相加,同时传递个给相关变量
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head><body><h3>可以按下按键ADSW移动图形</h3><canvas id='canvas'></canvas><script>let canvas = document.getElementById('canvas');let gl = canvas.getContext('webgl');let vertexShaderSource = `attribute vec2 a_Position;uniform vec2 u_Translation;void main(){gl_Position = vec4(u_Translation+a_Position,0.0,1.0) ; }`let fragmentShaderSouce = `precision mediump float;void main(){gl_FragColor = vec4(1.0,0.0,0.0,1.0);}`// 创建着色器let vertexShader = gl.createShader(gl.VERTEX_SHADER);// 设置着色器源代码gl.shaderSource(vertexShader, vertexShaderSource);// 编译着色器gl.compileShader(vertexShader)// 创建片段着色器let fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);// 设置片段着色器源代码gl.shaderSource(fragmentShader, fragmentShaderSouce);// 编译片段着色器gl.compileShader(fragmentShader)// 创建渲染程序let program = gl.createProgram();// 附着顶点着色器和片段着色器到渲染程序gl.attachShader(program, vertexShader);gl.attachShader(program, fragmentShader);// 链接渲染程序gl.linkProgram(program);//使用当前渲染程序gl.useProgram(program)//检测上述定点片源着色器链接是否正确if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {throw gl.getProgramInfoLog(program);}// x移动的增加量let translationX = 0.0;// y移动的增加量let translationY = 0.0;// 绘制三角形的顶点let positonArray = new Float32Array([1.0, 0.0, -1.0, 0.0, 0.0, -1.0])// 获取顶点着色器中的a_Position变量let a_Position = gl.getAttribLocation(program, 'a_Position');//获取顶点着色器中的u_Translation变量let u_Translation = gl.getUniformLocation(program, 'u_Translation');//创建缓冲区对象let buffer = gl.createBuffer();//将缓冲区对象绑定到目标gl.bindBuffer(gl.ARRAY_BUFFER, buffer);// 向缓冲区对象写入数据gl.bufferData(gl.ARRAY_BUFFER, positonArray, gl.STATIC_DRAW);// 将缓冲区对象分配给a_Position变量gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0);// 启用顶点位置的顶点着色器变量gl.enableVertexAttribArray(a_Position);//绘制gl.clearColor(0.0, 0.0, 0.0, 1.0);const render = function () {// 设置xy的移动增加的量gl.uniform2f(u_Translation, translationX, translationY)// 清除颜色缓冲区gl.clear(gl.COLOR_BUFFER_BIT);// 绘制三角形gl.drawArrays(gl.TRIANGLES, 0, 3)}render()document.onkeydown = function (e) { //对整个页面监听 var keyNum = window.event ? e.keyCode : e.which; //获取被按下的键值 //判断如果用户按下了回车键(keycody=13) if (keyNum == 65) {console.log('A');translationX -= 0.1; render()}//判断如果用户按下了空格键(keycode=32), if (keyNum == 68) {console.log('D');translationX += 0.1; render()}//判断如果用户按下了空格键(keycode=32), if (keyNum == 83) {console.log('S');translationY -= 0.1; render()}//判断如果用户按下了空格键(keycode=32), if (keyNum == 87) {console.log('W');translationY += 0.1; render();}}</script>
</body></html>