HUD(平视显示器)实现
1. demo效果
如上图,在三维场景中叠加了二维文本
2.实现要点
2.1 什么是HUD
HUD是 平视显示器 (head up display) 的简称,最早用于飞机驾驶显示器上,将飞机的一些重要信息投影到前方的玻璃上,这样就不用低头看仪表盘了,在游戏中,也经常会在三维场景上叠加一些二维文本或二维图形信息
2.2 HUD实现
2.2.1 准备画布
实现HUD需要准备两个标签,一个用来绘制三维图形,一个用来绘制二区HUD信息,然后将它们重叠放置,并将HUD的放在上面
<canvas id="webgl" width="800" height="800" style="position: absolute; z-index: 0"></canvas>
<canvas id="hud" width="800" height="800" style="position: absolute; z-index: 1"></canvas>
2.2.2 绘制三维图形
在第一个canvas上绘制三维图形,通过WebGL的API绘制三维图形,这里需要注意的一点事,之前的demo中鼠标点击事件是注册在获取的webgl的画布对象上,但这一次将HUD的canvas放在最上面,所以要在HUD的canvas注册点击事件,否则点击事件不会生效
//在二维画布上注册鼠标点击事件
hud.onmousedown = function (ev) {
var x = ev.clientX
var y = ev.clientY
var rect = ev.target.getBoundingClientRect()
if (rect.left <= x && x < rect.right && rect.top <= y && y < rect.bottom) {
//获取点击位置在canvas坐标系中的值
var x_in_canvas = x - rect.left
var y_in_canvas = rect.bottom - y
checkCubeIsSelected(gl, n, x_in_canvas, y_in_canvas, currentAngle, u_Clicked, viewProjMatrix, u_MvpMatrix)
}
}
2.2.3 绘制HUD信息
在第二个canvas上绘制HUD信息,具体绘制过程参照如下代码
function draw2D(ctx, currentAngle) {
ctx.clearRect(0, 0, 800, 800); //设置绘图区域
//绘制白色三角形
ctx.beginPath();
ctx.moveTo(240, 20);
ctx.lineTo(400, 300);
ctx.lineTo(80, 300);
ctx.closePath();
ctx.strokeStyle = 'rgba(255, 255, 255, 1)'; //线条颜色设置为白色
ctx.stroke(); //使用白色线绘制三角形
//绘制文字
ctx.font = '36px "Times New Roman"';
ctx.fillStyle = 'rgba(255, 255, 255, 1)'; //设置文字颜色为白色
ctx.fillText('HUD: Head Up Display', 80, 360);
ctx.fillText('Triangle is drawn by Canvas 2D API.', 80, 400);
ctx.fillText('Cube is drawn by WebGL API.', 80, 440);
ctx.fillText('Current Angle: ' + Math.floor(currentAngle), 80, 480);
}
3.demo代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<!--通过canvas标签创建一个800px*800px大小的画布-->
<canvas id="webgl" width="800" height="800" style="position: absolute; z-index: 0"></canvas>
<canvas id="hud" width="800" height="800" style="position: absolute; z-index: 1"></canvas>
<script type="text/javascript" src="./lib/cuon-matrix.js"></script>
<script>
//顶点着色器
var VSHADER_SOURCE = '' +
'attribute vec4 a_Position;\\n' + //声明attribute变量a_Position,用来存放顶点位置信息
'attribute vec4 a_Color;\\n' + //声明attribute变量a_Color,用来存放顶点颜色信息
'uniform mat4 u_MvpMatrix;\\n' + //声明uniform变量u_MvpMatrix,用来存放模型视图投影组合矩阵
'uniform bool u_Clicked;\\n' + //声明uniform变量u_Clicked,用来存放鼠标是否选中方块
'varying vec4 v_Color;\\n' + //声明varying变量v_Color,用来向片元着色器传值顶点颜色信息
'void main(){\\n' +
' gl_Position = u_MvpMatrix * a_Position;\\n' + //将模型视图投影组合矩阵与顶点坐标相乘赋值给顶点着色器内置变量gl_Position
' if (u_Clicked) {\\n' + //选中时方块绘制红色
' v_Color = vec4(1.0, 0.0, 0.0, 1.0);\\n' +
' } else {\\n' +
' v_Color = a_Color;\\n' + //将顶点颜色传给片元着色器
' }\\n' +
'}\\n'
//片元着色器
var FSHADER_SOURCE = '' +
'#ifdef GL_ES\\n' +
' precision mediump float;\\n' + // 设置精度
'#endif\\n' +
'varying vec4 v_Color;\\n' + //声明varying变量v_Color,用来接收顶点着色器传送的片元颜色信息
'void main(){\\n' +
' gl_FragColor = v_Color;\\n' + //将顶点着色器传送的片元颜色赋值给内置变量gl_FragColor
'}\\n'
//初始化着色器函数
function initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE) {
//创建顶点着色器对象
var vertexShader = loadShader(gl, gl.VERTEX_SHADER, VSHADER_SOURCE)
//创建片元着色器对象
var fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, FSHADER_SOURCE)
if (!vertexShader || !fragmentShader) {
return null
}
//创建程序对象program
var program = gl.createProgram()
if (!gl.createProgram()) {
return null
}
//分配顶点着色器和片元着色器到program
gl.attachShader(program, vertexShader)
gl.attachShader(program, fragmentShader)
//链接program
gl.linkProgram(program)
//检查程序对象是否连接成功
var linked = gl.getProgramParameter(program, gl.LINK_STATUS)
if (!linked) {
var error = gl.getProgramInfoLog(program)
console.log('程序对象连接失败: ' + error)
gl.deleteProgram(program)
gl.deleteShader(fragmentShader)
gl.deleteShader(vertexShader)
return null
}
//使用program
gl.useProgram(program)
gl.program = program
//返回程序program对象
return program
}
function loadShader(gl, type, source) {
// 创建顶点着色器对象
var shader = gl.createShader(type)
if (shader == null) {
console.log('创建着色器失败')
return null
}
// 引入着色器源代码
gl.shaderSource(shader, source)
// 编译着色器
gl.compileShader(shader)
// 检查顶是否编译成功
var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS)
if (!compiled) {
var error = gl.getShaderInfoLog(shader)
console.log('编译着色器失败: ' + error)
gl.deleteShader(shader)
return null
}
return shader
}
function init() {
//通过getElementById()方法获取canvas画布
var canvas = document.getElementById('webgl')
//通过方法getContext()获取WebGL上下文
var gl = canvas.getContext('webgl')
//初始化着色器
if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
console.log('初始化着色器失败')
return
}
//获取二维画布的上下文
var ctx = document.getElementById('hud').getContext('2d')
// 设置canvas的背景色
gl.clearColor(0.0, 0.0, 0.0, 1.0)
//初始化顶点坐标和顶点颜色
var n = initVertexBuffers(gl)
setMatrixAndDraw(gl, n, canvas, ctx)
}
//设置矩阵并绘图
function setMatrixAndDraw(gl, n, canvas, ctx) {
//开启隐藏面消除
gl.enable(gl.DEPTH_TEST)
//清空颜色和深度缓冲区
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
//获取顶点着色器uniform变量u_MvpMatrix、u_Clicked的存储地址
var u_MvpMatrix = gl.getUniformLocation(gl.program, 'u_MvpMatrix')
var u_Clicked = gl.getUniformLocation(gl.program, 'u_Clicked')
if (!u_MvpMatrix || !u_Clicked) {
console.log('获取uniform变量u_MvpMatrix或u_Clicked的存储地址失败')
return
}
//创建视图投影矩阵
var viewProjMatrix = new Matrix4()
viewProjMatrix.setPerspective(30.0, canvas.width / canvas.height, 1.0, 100.0)
viewProjMatrix.lookAt(0.0, 0.0, 7.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0)
gl.uniform1i(u_Clicked, 0) //给顶点着色器uniform变量u_Clicked传值
var currentAngle = 0.0 // 当前旋转的角度
//在二维画布上注册鼠标点击事件
hud.onmousedown = function (ev) {
var x = ev.clientX
var y = ev.clientY
var rect = ev.target.getBoundingClientRect()
if (rect.left <= x && x < rect.right && rect.top <= y && y < rect.bottom) {
//获取点击位置在canvas坐标系中的值
var x_in_canvas = x - rect.left
var y_in_canvas = rect.bottom - y
checkCubeIsSelected(gl, n, x_in_canvas, y_in_canvas, currentAngle, u_Clicked, viewProjMatrix, u_MvpMatrix)
}
}
var tick = function () { //动画循环
currentAngle = getCurrentAngle(currentAngle)
draw2D(ctx, currentAngle)
draw(gl, n, currentAngle, viewProjMatrix, u_MvpMatrix)
requestAnimationFrame(tick, canvas)
}
tick()
}
function draw2D(ctx, currentAngle) {
ctx.clearRect(0, 0, 800, 800); //设置绘图区域
//绘制白色三角形
ctx.beginPath();
ctx.moveTo(240, 20);
ctx.lineTo(400, 300);
ctx.lineTo(80, 300);
ctx.closePath();
ctx.strokeStyle = 'rgba(255, 255, 255, 1)'; //线条颜色设置为白色
ctx.stroke(); //使用白色线绘制三角形
//绘制文字
ctx.font = '36px "Times New Roman"';
ctx.fillStyle = 'rgba(255, 255, 255, 1)'; //设置文字颜色为白色
ctx.fillText('HUD: Head Up Display', 80, 360);
ctx.fillText('Triangle is drawn by Canvas 2D API.', 80, 400);
ctx.fillText('Cube is drawn by WebGL API.', 80, 440);
ctx.fillText('Current Angle: ' + Math.floor(currentAngle), 80, 480);
}
//初始化顶点坐标和顶点颜色
function initVertexBuffers(gl) {
var v0 = [1.0, 1.0, 1.0]
var v1 = [-1.0, 1.0, 1.0]
var v2 = [-1.0, -1.0, 1.0]
var v3 = [1.0, -1.0, 1.0]
var v4 = [1.0, -1.0, -1.0]
var v5 = [1.0, 1.0, -1.0]
var v6 = [-1.0, 1.0, -1.0]
var v7 = [-1.0, -1.0, -1.0]
//顶点
var vertices = new Float32Array([
...v0, ...v1, ...v2, ...v3, // 前
...v0, ...v3, ...v4, ...v5, // 右
...v0, ...v5, ...v6, ...v1, // 上
...v1, ...v6, ...v7, ...v2, // 左
...v7, ...v4, ...v3, ...v2, // 下
...v4, ...v7, ...v6, ...v5 // 后
])
var fontColor = [0.2, 0.58, 0.82]
var backColor = [0.73, 0.82, 0.93]
var leftColor = [0.78, 0.69, 0.84]
var rightColor = [0.5, 0.41, 0.69]
var topColor = [0.0, 0.32, 0.61]
var downColor = [0.32, 0.18, 0.56]
// 顶点的颜色
var colors = new Float32Array([
...fontColor, ...fontColor, ...fontColor, ...fontColor, // v0-v1-v2-v3 前
...rightColor, ...rightColor, ...rightColor, ...rightColor, // v0-v3-v4-v5 右
...topColor, ...topColor, ...topColor, ...topColor, // v0-v5-v6-v1 上
...leftColor, ...leftColor, ...leftColor, ...leftColor, // v1-v6-v7-v2 左
...downColor, ...downColor, ...downColor, ...downColor, // v7-v4-v3-v2 下
...backColor, ...backColor, ...backColor, ...backColor, // v4-v7-v6-v5 后
])
// 绘制的索引
var indices = new Uint8Array([
0, 1, 2, 0, 2, 3, // 前
4, 5, 6, 4, 6, 7, // 右
8, 9, 10, 8, 10, 11, // 上
12, 13, 14, 12, 14, 15, // 左
16, 17, 18, 16, 18, 19, // 下
20, 21, 22, 20, 22, 23 // 后
])
if (!initArrayBuffer(gl, vertices, 3, gl.FLOAT, 'a_Position')) {
return -1
}
if (!initArrayBuffer(gl, colors, 3, gl.FLOAT, 'a_Color')) {
return -1
}
//创建缓冲区对象
var indexBuffer = gl.createBuffer()
//将顶点索引写入缓冲区对象
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer)
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW)
return indices.length
}
//检查点击是否在方块上
function checkCubeIsSelected(gl, n, x, y, currentAngle, u_Clicked, viewProjMatrix, u_MvpMatrix) {
gl.uniform1i(u_Clicked, 1) //给顶点着色器uniform变量u_Clicked传值1
//绘制图形,顶点着色器中根据u_Clicked值将方块绘制为红色,即RGBA值的R分量为255
draw(gl, n, currentAngle, viewProjMatrix, u_MvpMatrix)
var pixels = new Uint8Array(4) //创建Uint8Array类型化数组,接收获取的像素值数据
gl.readPixels(x, y, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixels) //读取鼠标点击位置像素颜色
if (pixels[0] == 255) // pixels[0]即RGBA值的R分量的值等于255说明选中方块
{
alert('方块被选中! ')
}
gl.uniform1i(u_Clicked, 0)
draw(gl, n, currentAngle, viewProjMatrix, u_MvpMatrix) // 重绘方块
}
var g_MvpMatrix = new Matrix4() //模型视图投影矩阵
function draw(gl, n, currentAngle, viewProjMatrix, u_MvpMatrix) {
//计算模型视图投影矩阵
g_MvpMatrix.set(viewProjMatrix)
g_MvpMatrix.rotate(currentAngle, 1.0, 0.0, 0.0)
g_MvpMatrix.rotate(currentAngle, 0.0, 1.0, 0.0)
g_MvpMatrix.rotate(currentAngle, 0.0, 0.0, 1.0)
//模型视图投影矩阵的计算结果传给uniform变量u_MvpMatrix
gl.uniformMatrix4fv(u_MvpMatrix, false, g_MvpMatrix.elements)
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
gl.drawElements(gl.TRIANGLES, n, gl.UNSIGNED_BYTE, 0) //绘图
}
var g_LastTime = Date.now() // 上次绘制的时间
var ANGLE_SET = 30.0 // 旋转速度(度/秒)
function getCurrentAngle(angle) {
var now = Date.now()
var elapsed = now - g_LastTime //上次调用与当前时间差
g_LastTime = now
var newAngle = angle + (ANGLE_SET * elapsed) / 1000.0
return newAngle %= 360
}
function initArrayBuffer(gl, data, num, type, attribute) {
//创建缓冲区对象
var buffer = gl.createBuffer()
//将顶点坐标和顶点颜色信息写入缓冲区对象
gl.bindBuffer(gl.ARRAY_BUFFER, buffer)
gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW)
//获取顶点着色器attribute变量存储地址, 分配缓存并开启
var a_Attribute = gl.getAttribLocation(gl.program, attribute)
gl.vertexAttribPointer(a_Attribute, num, type, false, 0, 0)
gl.enableVertexAttribArray(a_Attribute)
return true
}
init()
</script>
</body>
</html>
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
暂无评论内容