在上一篇教程《WebGL簡易教程(七):繪製一個矩形體》中,經過一個繪製矩形包圍盒的實例,進一步理解了模型視圖投影變換。其實,三維場景的UI交互工做正是基於模型視圖投影變換的基礎之上的。這裏就經過以前的知識實現一個三維場景的瀏覽實例:經過鼠標實現場景的旋轉和縮放。html
改進上一篇教程的JS代碼,獲得新的代碼以下:java
// 頂點着色器程序 var VSHADER_SOURCE = 'attribute vec4 a_Position;\n' + // attribute variable 'attribute vec4 a_Color;\n' + 'uniform mat4 u_MvpMatrix;\n' + 'varying vec4 v_Color;\n' + 'void main() {\n' + ' gl_Position = u_MvpMatrix * a_Position;\n' + // Set the vertex coordinates of the point ' v_Color = a_Color;\n' + '}\n'; // 片元着色器程序 var FSHADER_SOURCE = 'precision mediump float;\n' + 'varying vec4 v_Color;\n' + 'void main() {\n' + ' gl_FragColor = v_Color;\n' + '}\n'; //定義一個矩形體:混合構造函數原型模式 function Cuboid(minX, maxX, minY, maxY, minZ, maxZ) { this.minX = minX; this.maxX = maxX; this.minY = minY; this.maxY = maxY; this.minZ = minZ; this.maxZ = maxZ; } Cuboid.prototype = { constructor: Cuboid, CenterX: function () { return (this.minX + this.maxX) / 2.0; }, CenterY: function () { return (this.minY + this.maxY) / 2.0; }, CenterZ: function () { return (this.minZ + this.maxZ) / 2.0; }, LengthX: function () { return (this.maxX - this.minX); }, LengthY: function () { return (this.maxY - this.minY); } } var currentAngle = [0.0, 0.0]; // 繞X軸Y軸的旋轉角度 ([x-axis, y-axis]) var curScale = 1.0; //當前的縮放比例 function main() { // 獲取 <canvas> 元素 var canvas = document.getElementById('webgl'); // 獲取WebGL渲染上下文 var gl = getWebGLContext(canvas); if (!gl) { console.log('Failed to get the rendering context for WebGL'); return; } // 初始化着色器 if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) { console.log('Failed to intialize shaders.'); return; } // 設置頂點位置 var cuboid = new Cuboid(399589.072, 400469.072, 3995118.062, 3997558.062, 732, 1268); var n = initVertexBuffers(gl, cuboid); if (n < 0) { console.log('Failed to set the positions of the vertices'); return; } //註冊鼠標事件 initEventHandlers(canvas); // 指定清空<canvas>的顏色 gl.clearColor(0.0, 0.0, 0.0, 1.0); // 開啓深度測試 gl.enable(gl.DEPTH_TEST); //繪製函數 var tick = function () { //設置MVP矩陣 setMVPMatrix(gl, canvas, cuboid); //清空顏色和深度緩衝區 gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); //繪製矩形體 gl.drawElements(gl.TRIANGLES, n, gl.UNSIGNED_BYTE, 0); //請求瀏覽器調用tick requestAnimationFrame(tick); }; //開始繪製 tick(); // 繪製矩形體 gl.drawElements(gl.TRIANGLES, n, gl.UNSIGNED_BYTE, 0); } //註冊鼠標事件 function initEventHandlers(canvas) { var dragging = false; // Dragging or not var lastX = -1, lastY = -1; // Last position of the mouse //鼠標按下 canvas.onmousedown = function (ev) { var x = ev.clientX; var y = ev.clientY; // Start dragging if a moue is in <canvas> var rect = ev.target.getBoundingClientRect(); if (rect.left <= x && x < rect.right && rect.top <= y && y < rect.bottom) { lastX = x; lastY = y; dragging = true; } }; //鼠標離開時 canvas.onmouseleave = function (ev) { dragging = false; }; //鼠標釋放 canvas.onmouseup = function (ev) { dragging = false; }; //鼠標移動 canvas.onmousemove = function (ev) { var x = ev.clientX; var y = ev.clientY; if (dragging) { var factor = 100 / canvas.height; // The rotation ratio var dx = factor * (x - lastX); var dy = factor * (y - lastY); currentAngle[0] = currentAngle[0] + dy; currentAngle[1] = currentAngle[1] + dx; } lastX = x, lastY = y; }; //鼠標縮放 canvas.onmousewheel = function (event) { if (event.wheelDelta > 0) { curScale = curScale * 1.1; } else { curScale = curScale * 0.9; } }; } //設置MVP矩陣 function setMVPMatrix(gl, canvas, cuboid) { // Get the storage location of u_MvpMatrix var u_MvpMatrix = gl.getUniformLocation(gl.program, 'u_MvpMatrix'); if (!u_MvpMatrix) { console.log('Failed to get the storage location of u_MvpMatrix'); return; } //模型矩陣 var modelMatrix = new Matrix4(); modelMatrix.scale(curScale, curScale, curScale); modelMatrix.rotate(currentAngle[0], 1.0, 0.0, 0.0); // Rotation around x-axis modelMatrix.rotate(currentAngle[1], 0.0, 1.0, 0.0); // Rotation around y-axis modelMatrix.translate(-cuboid.CenterX(), -cuboid.CenterY(), -cuboid.CenterZ()); //投影矩陣 var fovy = 60; var near = 1; var projMatrix = new Matrix4(); projMatrix.setPerspective(fovy, canvas.width / canvas.height, 1, 10000); //計算lookAt()函數初始視點的高度 var angle = fovy / 2 * Math.PI / 180.0; var eyeHight = (cuboid.LengthY() * 1.2) / 2.0 / angle; //視圖矩陣 var viewMatrix = new Matrix4(); // View matrix viewMatrix.lookAt(0, 0, eyeHight, 0, 0, 0, 0, 1, 0); //MVP矩陣 var mvpMatrix = new Matrix4(); mvpMatrix.set(projMatrix).multiply(viewMatrix).multiply(modelMatrix); //將MVP矩陣傳輸到着色器的uniform變量u_MvpMatrix gl.uniformMatrix4fv(u_MvpMatrix, false, mvpMatrix.elements); } // function initVertexBuffers(gl, cuboid) { // Create a cube // v6----- v5 // /| /| // v1------v0| // | | | | // | |v7---|-|v4 // |/ |/ // v2------v3 // 頂點座標和顏色 var verticesColors = new Float32Array([ cuboid.maxX, cuboid.maxY, cuboid.maxZ, 1.0, 1.0, 1.0, // v0 White cuboid.minX, cuboid.maxY, cuboid.maxZ, 1.0, 0.0, 1.0, // v1 Magenta cuboid.minX, cuboid.minY, cuboid.maxZ, 1.0, 0.0, 0.0, // v2 Red cuboid.maxX, cuboid.minY, cuboid.maxZ, 1.0, 1.0, 0.0, // v3 Yellow cuboid.maxX, cuboid.minY, cuboid.minZ, 0.0, 1.0, 0.0, // v4 Green cuboid.maxX, cuboid.maxY, cuboid.minZ, 0.0, 1.0, 1.0, // v5 Cyan cuboid.minX, cuboid.maxY, cuboid.minZ, 0.0, 0.0, 1.0, // v6 Blue cuboid.minX, cuboid.minY, cuboid.minZ, 1.0, 0.0, 1.0 // v7 Black ]); //頂點索引 var indices = new Uint8Array([ 0, 1, 2, 0, 2, 3, // 前 0, 3, 4, 0, 4, 5, // 右 0, 5, 6, 0, 6, 1, // 上 1, 6, 7, 1, 7, 2, // 左 7, 4, 3, 7, 3, 2, // 下 4, 7, 6, 4, 6, 5 // 後 ]); // var FSIZE = verticesColors.BYTES_PER_ELEMENT; //數組中每一個元素的字節數 // 建立緩衝區對象 var vertexColorBuffer = gl.createBuffer(); var indexBuffer = gl.createBuffer(); if (!vertexColorBuffer || !indexBuffer) { console.log('Failed to create the buffer object'); return -1; } // 將緩衝區對象綁定到目標 gl.bindBuffer(gl.ARRAY_BUFFER, vertexColorBuffer); // 向緩衝區對象寫入數據 gl.bufferData(gl.ARRAY_BUFFER, verticesColors, gl.STATIC_DRAW); //獲取着色器中attribute變量a_Position的地址 var a_Position = gl.getAttribLocation(gl.program, 'a_Position'); if (a_Position < 0) { console.log('Failed to get the storage location of a_Position'); return -1; } // 將緩衝區對象分配給a_Position變量 gl.vertexAttribPointer(a_Position, 3, gl.FLOAT, false, FSIZE * 6, 0); // 鏈接a_Position變量與分配給它的緩衝區對象 gl.enableVertexAttribArray(a_Position); //獲取着色器中attribute變量a_Color的地址 var a_Color = gl.getAttribLocation(gl.program, 'a_Color'); if (a_Color < 0) { console.log('Failed to get the storage location of a_Color'); return -1; } // 將緩衝區對象分配給a_Color變量 gl.vertexAttribPointer(a_Color, 3, gl.FLOAT, false, FSIZE * 6, FSIZE * 3); // 鏈接a_Color變量與分配給它的緩衝區對象 gl.enableVertexAttribArray(a_Color); // 將頂點索引寫入到緩衝區對象 gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW); return indices.length; }
與以前的代碼相比,這裏主要改進了兩個方面的內容:重繪刷新和鼠標事件調整參數。git
與以前只繪製一次場景不一樣,爲了知足瀏覽交互工做,頁面就必須實時刷新,來知足不一樣的鼠標、鍵盤事件對場景的影響。能夠使用JS的requestAnimationFrame()函數進行定時重繪刷新操做。其函數定義以下:
github
在代碼中的實現以下:web
//繪製函數 var tick = function () { //設置MVP矩陣 setMVPMatrix(gl, canvas, cuboid); //清空顏色和深度緩衝區 gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); //繪製矩形體 gl.drawElements(gl.TRIANGLES, n, gl.UNSIGNED_BYTE, 0); //請求瀏覽器調用tick requestAnimationFrame(tick); }; //開始繪製 tick();
在這段代碼中,定義了一個繪製函數tick(),而在該函數的結束處,調用了requestAnimationFrame()函數來向瀏覽器請求調用其回調函數,也就是tick()。以此循環往復,頁面會不停的請求調用繪製tick(),從而帶到了重繪刷新的效果。編程
前面提到過,重繪刷新每一幀以前,都要清空顏色緩衝區和深度緩衝區,不讓上一幀的效果影響到下一幀。同理,MVP矩陣也是每繪製一幀以前就須要從新設置的。canvas
在設置MVP矩陣函數setMVPMatrix()中,能夠發現視圖矩陣和投影矩陣都是初次計算好就固定的,只有模型矩陣隨着變量currentAngle和curScale變化而變化,相關代碼以下:數組
var currentAngle = [0.0, 0.0]; // 繞X軸Y軸的旋轉角度 ([x-axis, y-axis]) var curScale = 1.0; //當前的縮放比例 //設置MVP矩陣 function setMVPMatrix(gl, canvas, cuboid) { //... //模型矩陣 var modelMatrix = new Matrix4(); modelMatrix.scale(curScale, curScale, curScale); modelMatrix.rotate(currentAngle[0], 1.0, 0.0, 0.0); // Rotation around x-axis modelMatrix.rotate(currentAngle[1], 0.0, 1.0, 0.0); // Rotation around y-axis modelMatrix.translate(-cuboid.CenterX(), -cuboid.CenterY(), -cuboid.CenterZ()); //... }
currentAngle和curScale是預先定義的全局變量,它們在函數initEventHandlers中被設置。在initEventHandlers函數中,註冊了畫布元素canvas的鼠標事件。當鼠標在畫布視圖中拖動的時候,currentAngle根據鼠標在X、Y方向上位移變化而變化:瀏覽器
//鼠標按下 canvas.onmousedown = function (ev) { var x = ev.clientX; var y = ev.clientY; // Start dragging if a moue is in <canvas> var rect = ev.target.getBoundingClientRect(); if (rect.left <= x && x < rect.right && rect.top <= y && y < rect.bottom) { lastX = x; lastY = y; dragging = true; } }; //... //鼠標移動 canvas.onmousemove = function (ev) { var x = ev.clientX; var y = ev.clientY; if (dragging) { var factor = 100 / canvas.height; // The rotation ratio var dx = factor * (x - lastX); var dy = factor * (y - lastY); currentAngle[0] = currentAngle[0] + dy; currentAngle[1] = currentAngle[1] + dx; } lastX = x, lastY = y; };
當鼠標在畫布上滑動滾輪的時候,curScale根據滾動的幅度變化而變化:
//鼠標縮放 canvas.onmousewheel = function (event) { if (event.wheelDelta > 0) { curScale = curScale * 1.1; } else { curScale = curScale * 0.9; } };
currentAngle和curScale的變化使得模型矩陣發生改變,而每繪製一幀就會從新設置MVP矩陣,這就使得三維場景隨着鼠標操做而變化,從而完成交互操做。
在瀏覽器中打開對應的HTML文件,運行結果以下:
原本部分代碼和插圖來自《WebGL編程指南》,源代碼連接:地址 。會在此共享目錄中持續更新後續的內容。