基于之前教程的知識,實作了一個三維場景的浏覽執行個體:通過滑鼠實作場景的旋轉和縮放。
目錄
- 1. 概述
- 2. 執行個體
- 2.1. 重繪重新整理
- 2.2. 滑鼠事件調整參數
- 3. 結果
- 4. 參考
在上一篇教程《WebGL簡易教程(七):繪制一個矩形體》中,通過一個繪制矩形包圍盒的執行個體,進一步了解了模型視圖投影變換。其實,三維場景的UI互動工作正是基于模型視圖投影變換的基礎之上的。這裡就通過之前的知識實作一個三維場景的浏覽執行個體:通過滑鼠實作場景的旋轉和縮放。
改進上一篇教程的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;
}
與之前的代碼相比,這裡主要改進了兩個方面的内容:重繪重新整理和滑鼠事件調整參數。
與之前隻繪制一次場景不同,為了滿足浏覽互動工作,頁面就必須實時重新整理,來滿足不同的滑鼠、鍵盤事件對場景的影響。可以使用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矩陣也是每繪制一幀之前就需要重新設定的。
在設定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程式設計指南》,源代碼連結:位址 。會在此共享目錄中持續更新後續的内容。