1. 概述
在上一篇教程《WebGL簡易教程(七):繪制一個矩形體》中,通過一個繪制矩形包圍盒的實例,進一步理解了模型視圖投影變換。其實,三維場景的UI交互工作正是基於模型視圖投影變換的基礎之上的。這里就通過之前的知識實現一個三維場景的瀏覽實例:通過鼠標實現場景的旋轉和縮放。
2. 實例
改進上一篇教程的JS代碼,得到新的代碼如下:
// 頂點着色器程序
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;
}
與之前的代碼相比,這里主要改進了兩個方面的內容:重繪刷新和鼠標事件調整參數。
2.1. 重繪刷新
與之前只繪制一次場景不同,為了滿足瀏覽交互工作,頁面就必須實時刷新,來滿足不同的鼠標、鍵盤事件對場景的影響。可以使用JS的requestAnimationFrame()函數進行定時重繪刷新操作。其函數定義如下:
在代碼中的實現如下:
//繪制函數
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矩陣也是每繪制一幀之前就需要重新設置的。
2.2. 鼠標事件調整參數
在設置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矩陣,這就使得三維場景隨着鼠標操作而變化,從而完成交互操作。
3. 結果
在瀏覽器中打開對應的HTML文件,運行結果如下:
4. 參考
本來部分代碼和插圖來自《WebGL編程指南》,源代碼鏈接:地址 。會在此共享目錄中持續更新后續的內容。