1. 具体实例

通过WebGL,可以渲染生成DEM(数字高程模型)。DEM(数字高程模型)是网格点组成的模型,每个点都有x,y,z值;x,y根据一定的间距组成网格状,同时根据z值的高低来选定每个点的颜色RGB。通过这个例子可以熟悉WebGL颜色渲染的过程。

2. 解决方案

1) DEM数据.XYZ文件

这里使用的DEM文件的数据组织如下,如下图所示。



其中每一行表示一个点,前三个数值表示位置XYZ,后三个数值表示颜色RGB。

2) showDEM.html

<!DOCTYPE html>
<html> <head>
<meta charset="UTF-8">
<title> 显示地形 </title>
<script src="lib/webgl-utils.js"></script>
<script src="lib/webgl-debug.js"></script>
<script src="lib/cuon-utils.js"></script>
<script src="lib/cuon-matrix.js"></script>
<script src="showDEM.js"></script>
</head> <body>
<div><input type = 'file' id = 'demFile' ></div>
<!-- <div><textarea id="output" rows="300" cols="200"></textarea></div> -->
<div>
<canvas id ="demCanvas" width="600" height="600">
请使用支持WebGL的浏览器
</canvas>
</div>
</body> </html>

3) showDEM.js

// Vertex shader program
var VSHADER_SOURCE =
//'precision highp float;\n' +
'attribute vec4 a_Position;\n' +
'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' +
' v_Color = a_Color;\n' +
'}\n'; // Fragment shader program
var FSHADER_SOURCE =
'#ifdef GL_ES\n' +
'precision mediump float;\n' +
'#endif\n' +
'varying vec4 v_Color;\n' +
'void main() {\n' +
' gl_FragColor = v_Color;\n' +
'}\n'; //
var col = 89; //DEM宽
var row = 245; //DEM高 // Current rotation angle ([x-axis, y-axis] degrees)
var currentAngle = [0.0, 0.0]; //当前lookAt()函数初始视点的高度
var eyeHight = 2000.0; //setPerspective()远截面
var far = 3000; //
window.onload = function () {
var demFile = document.getElementById('demFile');
if (!demFile) {
console.log("Error!");
return;
} //demFile.onchange = openFile(event);
demFile.addEventListener("change", function (event) {
//判断浏览器是否支持FileReader接口
if (typeof FileReader == 'undefined') {
console.log("你的浏览器不支持FileReader接口!");
return;
} //
var reader = new FileReader();
reader.onload = function () {
if (reader.result) {
//
var stringlines = reader.result.split("\n");
verticesColors = new Float32Array(stringlines.length * 6); //
var pn = 0;
var ci = 0;
for (var i = 0; i < stringlines.length; i++) {
if (!stringlines[i]) {
continue;
}
var subline = stringlines[i].split(',');
if (subline.length != 6) {
console.log("错误的文件格式!");
return;
}
for (var j = 0; j < subline.length; j++) {
verticesColors[ci] = parseFloat(subline[j]);
ci++;
}
pn++;
} if (ci < 3) {
console.log("错误的文件格式!");
} //
var minX = verticesColors[0];
var maxX = verticesColors[0];
var minY = verticesColors[1];
var maxY = verticesColors[1];
var minZ = verticesColors[2];
var maxZ = verticesColors[2];
for (var i = 0; i < pn; i++) {
minX = Math.min(minX, verticesColors[i * 6]);
maxX = Math.max(maxX, verticesColors[i * 6]);
minY = Math.min(minY, verticesColors[i * 6 + 1]);
maxY = Math.max(maxY, verticesColors[i * 6 + 1]);
minZ = Math.min(minZ, verticesColors[i * 6 + 2]);
maxZ = Math.max(maxZ, verticesColors[i * 6 + 2]);
} //包围盒中心
var cx = (minX + maxX) / 2.0;
var cy = (minY + maxY) / 2.0;
var cz = (minZ + maxZ) / 2.0; //根据视点高度算出setPerspective()函数的合理角度
var fovy = (maxY - minY) / 2.0 / eyeHight;
fovy = 180.0 / Math.PI * Math.atan(fovy) * 2; startDraw(verticesColors, cx, cy, cz, fovy);
}
}; //
var input = event.target;
reader.readAsText(input.files[0]);
});
} function startDraw(verticesColors, cx, cy, cz, fovy) {
// Retrieve <canvas> element
var canvas = document.getElementById('demCanvas'); // Get the rendering context for WebGL
var gl = getWebGLContext(canvas);
if (!gl) {
console.log('Failed to get the rendering context for WebGL');
return;
} // Initialize shaders
if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
console.log('Failed to intialize shaders.');
return;
} // Set the vertex coordinates and color (the blue triangle is in the front)
n = initVertexBuffers(gl, verticesColors); //, verticesColors, n
if (n < 0) {
console.log('Failed to set the vertex information');
return;
} // 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;
} // Register the event handler
initEventHandlers(canvas); // Specify the color for clearing <canvas>
gl.clearColor(0, 0, 0, 1);
gl.enable(gl.DEPTH_TEST); // Start drawing
var tick = function () { //setPerspective()宽高比
var aspect = canvas.width / canvas.height; //
draw(gl, n, aspect, cx, cy, cz, fovy, u_MvpMatrix);
requestAnimationFrame(tick, canvas);
};
tick();
} //
function initEventHandlers(canvas) {
var dragging = false; // Dragging or not
var lastX = -1, lastY = -1; // Last position of the mouse // Mouse is pressed
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;
}; // Mouse is released
canvas.onmouseup = function (ev) {
dragging = false;
}; // Mouse is moved
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);
// Limit x-axis rotation angle to -90 to 90 degrees
//currentAngle[0] = Math.max(Math.min(currentAngle[0] + dy, 90.0), -90.0);
currentAngle[0] = currentAngle[0] + dy;
currentAngle[1] = currentAngle[1] + dx;
}
lastX = x, lastY = y;
}; //鼠标缩放
canvas.onmousewheel = function (event) {
var lastHeight = eyeHight;
if (event.wheelDelta > 0) {
eyeHight = Math.max(1, eyeHight - 80);
} else {
eyeHight = eyeHight + 80;
} far = far + eyeHight - lastHeight;
};
} function draw(gl, n, aspect, cx, cy, cz, fovy, u_MvpMatrix) {
//模型矩阵
var modelMatrix = new Matrix4();
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(-cx, -cy, -cz); //视图矩阵
var viewMatrix = new Matrix4();
viewMatrix.lookAt(0, 0, eyeHight, 0, 0, 0, 0, 1, 0); //投影矩阵
var projMatrix = new Matrix4();
projMatrix.setPerspective(fovy, aspect, 10, far); //模型视图投影矩阵
var mvpMatrix = new Matrix4();
mvpMatrix.set(projMatrix).multiply(viewMatrix).multiply(modelMatrix); // Pass the model view projection matrix to u_MvpMatrix
gl.uniformMatrix4fv(u_MvpMatrix, false, mvpMatrix.elements); // Clear color and depth buffer
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); // Draw the cube
gl.drawElements(gl.TRIANGLES, n, gl.UNSIGNED_SHORT, 0);
} function initVertexBuffers(gl, verticesColors) {
//DEM的一个网格是由两个三角形组成的
// 0------1 1
// | |
// | |
// col col------col+1
var indices = new Uint16Array((row - 1) * (col - 1) * 6);
var ci = 0;
for (var yi = 0; yi < row - 1; yi++) {
for (var xi = 0; xi < col - 1; xi++) {
indices[ci * 6] = yi * col + xi;
indices[ci * 6 + 1] = (yi + 1) * col + xi;
indices[ci * 6 + 2] = yi * col + xi + 1;
indices[ci * 6 + 3] = (yi + 1) * col + xi;
indices[ci * 6 + 4] = (yi + 1) * col + xi + 1;
indices[ci * 6 + 5] = yi * col + xi + 1;
ci++;
}
} //创建缓冲区对象
var vertexColorBuffer = gl.createBuffer();
var indexBuffer = gl.createBuffer();
if (!vertexColorBuffer || !indexBuffer) {
return -1;
} // 将缓冲区对象绑定到目标
gl.bindBuffer(gl.ARRAY_BUFFER, vertexColorBuffer);
// 向缓冲区对象中写入数据
gl.bufferData(gl.ARRAY_BUFFER, verticesColors, gl.STATIC_DRAW); //
var FSIZE = verticesColors.BYTES_PER_ELEMENT;
// 向缓冲区对象分配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;
}
gl.vertexAttribPointer(a_Position, 3, gl.FLOAT, false, FSIZE * 6, 0);
//开启a_Position变量
gl.enableVertexAttribArray(a_Position); // 向缓冲区对象分配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;
}
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;
}

4) 运行结果

用chrome打开showDEM.html,选择DEM文件,界面就会显示DEM的渲染效果:

3. 详细讲解

1) 读取文件

程序的第一步是通过JS的FileReader()函数读取DEM文件,在其回调函数中读取到数组verticesColors中,它包含了位置和颜色信息。读取完成后调用绘制函数startDraw()。

//
var reader = new FileReader();
reader.onload = function () {
if (reader.result) {
//
var stringlines = reader.result.split("\n");
verticesColors = new Float32Array(stringlines.length * 6); //
var pn = 0;
var ci = 0;
for (var i = 0; i < stringlines.length; i++) {
if (!stringlines[i]) {
continue;
}
var subline = stringlines[i].split(',');
if (subline.length != 6) {
console.log("错误的文件格式!");
return;
}
for (var j = 0; j < subline.length; j++) {
verticesColors[ci] = parseFloat(subline[j]);
ci++;
}
pn++;
} if (ci < 3) {
console.log("错误的文件格式!");
} //
var minX = verticesColors[0];
var maxX = verticesColors[0];
var minY = verticesColors[1];
var maxY = verticesColors[1];
var minZ = verticesColors[2];
var maxZ = verticesColors[2];
for (var i = 0; i < pn; i++) {
minX = Math.min(minX, verticesColors[i * 6]);
maxX = Math.max(maxX, verticesColors[i * 6]);
minY = Math.min(minY, verticesColors[i * 6 + 1]);
maxY = Math.max(maxY, verticesColors[i * 6 + 1]);
minZ = Math.min(minZ, verticesColors[i * 6 + 2]);
maxZ = Math.max(maxZ, verticesColors[i * 6 + 2]);
} //包围盒中心
var cx = (minX + maxX) / 2.0;
var cy = (minY + maxY) / 2.0;
var cz = (minZ + maxZ) / 2.0; //根据视点高度算出setPerspective()函数的合理角度
var fovy = (maxY - minY) / 2.0 / eyeHight;
fovy = 180.0 / Math.PI * Math.atan(fovy) * 2; startDraw(verticesColors, cx, cy, cz, fovy);
}
}; //
var input = event.target;
reader.readAsText(input.files[0]);

2) 绘制函数

绘制DEM跟绘制一个简单三角形的步骤是差不多的:

  1. 获取WebGL环境。
  2. 初始化shaders,构建着色器。
  3. 初始化顶点数组,分配到缓冲对象。
  4. 绑定鼠标键盘事件,设置模型视图投影变换矩阵。
  5. 在重绘函数中调用WebGL函数绘制。

其中最关键的步骤是第三步,初始化顶点数组initVertexBuffers()。

function startDraw(verticesColors, cx, cy, cz, fovy) {
// Retrieve <canvas> element
var canvas = document.getElementById('demCanvas'); // Get the rendering context for WebGL
var gl = getWebGLContext(canvas);
if (!gl) {
console.log('Failed to get the rendering context for WebGL');
return;
} // Initialize shaders
if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
console.log('Failed to intialize shaders.');
return;
} // Set the vertex coordinates and color (the blue triangle is in the front)
n = initVertexBuffers(gl, verticesColors); //, verticesColors, n
if (n < 0) {
console.log('Failed to set the vertex information');
return;
} // 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;
} // Register the event handler
initEventHandlers(canvas); // Specify the color for clearing <canvas>
gl.clearColor(0, 0, 0, 1);
gl.enable(gl.DEPTH_TEST); // Start drawing
var tick = function () { //setPerspective()宽高比
var aspect = canvas.width / canvas.height; //
draw(gl, n, aspect, cx, cy, cz, fovy, u_MvpMatrix);
requestAnimationFrame(tick, canvas);
};
tick();
}

3) 使用缓冲区对象

在函数initVertexBuffers()中包含了使用缓冲区对象向顶点着色器传入多个顶点数据的过程:

  1. 创建缓冲区对象(gl.createBuffer());
  2. 绑定缓冲区对象(gl.bindBuffer());
  3. 将数据写入缓冲区对象(gl.bufferData);
  4. 将缓冲区对象分配给一个attribute变量(gl.vertexAttribPointer)
  5. 开启attribute变量(gl.enableVertexAttribArray);

在本例中,在JS中申请的数组verticesColors分成位置和颜色两部分分配给缓冲区对象,并传入顶点着色器;vertexAttribPointer()是其关键的函数,需要详细了解其参数的用法。最后,把顶点数据的索引值绑定到缓冲区对象,WebGL可以访问索引来间接访问顶点数据进行绘制。

function initVertexBuffers(gl, verticesColors) {
//DEM的一个网格是由两个三角形组成的
// 0------1 1
// | |
// | |
// col col------col+1
var indices = new Uint16Array((row - 1) * (col - 1) * 6);
var ci = 0;
for (var yi = 0; yi < row - 1; yi++) {
for (var xi = 0; xi < col - 1; xi++) {
indices[ci * 6] = yi * col + xi;
indices[ci * 6 + 1] = (yi + 1) * col + xi;
indices[ci * 6 + 2] = yi * col + xi + 1;
indices[ci * 6 + 3] = (yi + 1) * col + xi;
indices[ci * 6 + 4] = (yi + 1) * col + xi + 1;
indices[ci * 6 + 5] = yi * col + xi + 1;
ci++;
}
} //创建缓冲区对象
var vertexColorBuffer = gl.createBuffer();
var indexBuffer = gl.createBuffer();
if (!vertexColorBuffer || !indexBuffer) {
return -1;
} // 将缓冲区对象绑定到目标
gl.bindBuffer(gl.ARRAY_BUFFER, vertexColorBuffer);
// 向缓冲区对象中写入数据
gl.bufferData(gl.ARRAY_BUFFER, verticesColors, gl.STATIC_DRAW); //
var FSIZE = verticesColors.BYTES_PER_ELEMENT;
// 向缓冲区对象分配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;
}
gl.vertexAttribPointer(a_Position, 3, gl.FLOAT, false, FSIZE * 6, 0);
//开启a_Position变量
gl.enableVertexAttribArray(a_Position); // 向缓冲区对象分配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;
}
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;
}

4. 其他

1.这里用到了几个《WebGL编程指南》书中提供的JS组件。全部源代码(包含DEM数据)地址链接:https://share.weiyun.com/5cvt8PJ ,密码:4aqs8e。

2.如果关心如何设置模型视图投影变换矩阵,以及绑定鼠标键盘事件,可参看这篇文章:WebGL或OpenGL关于模型视图投影变换的设置技巧

3.渲染的结果如果加入光照,效果会更好。

WebGL的颜色渲染-渲染一张DEM(数字高程模型)的更多相关文章

  1. WebGIS 利用 WebGL 在 MapboxGL 上渲染 DEM 三维空间数据

    毕业两年,一直在地图相关的公司工作,虽然不是 GIS 出身,但是也对地图有些耳濡目染:最近在看 WebGl 的东西,就拿 MapboxGL 做了一个关于 WebGL 的三维数据渲染的 DEMO 练手. ...

  2. WebGL 纹理颜色原理

    本文由云+社区发表 作者:ivweb qcyhust 导语 WebGL绘制图像时,往着色器中传入颜色信息就可以给图形绘制出相应的颜色,现在已经知道顶点着色器和片段着色器一起决定着向颜色缓冲区写入颜色信 ...

  3. [WebGL入门]四,渲染准备

    注意:文章翻译http://wgld.org/,原作者杉本雅広(doxas),文章中假设有我的额外说明,我会加上[lufy:].另外.鄙人webgl研究还不够深入,一些专业词语,假设翻译有误,欢迎大家 ...

  4. 基于WebGL的三维地形渲染

    1.生成WebMap页面 #!/usr/bin/env python # -*- coding: utf-8 -*- import subprocess from jinja2 import Envi ...

  5. vue打包空白,图片没加载,背景颜色没有渲染出来-配置秘诀

    找到config文件夹下的index.js文件修改一下位置 看清楚是 build(上边还有个dev 是开发环境下的配置,不需要改动)下的 assetsPublicPath :将‘/’改为‘./’ 在c ...

  6. 用ARCGIS配出一张DEM专题图

    专题图是指突出而尽可能完善.详尽地表达制图区内的一种或几种自然或社会经济要素的地图.专题图的制图领域宽广,凡具有空间属性的信息数据都可以用其来表示.由于DEM描述的是地面高程信息,它在测绘.水文.气象 ...

  7. layui下拉框数据过万渲染渲染问题解决方案

    方案一:layui下拉框分页插件 https://fly.layui.com/jie/29002/ 此插件我用了下浏览器缓存有问题,而且当下拉框数据量过万后,会一直渲染不出来,期待后期作者优化 如图下 ...

  8. 赛门铁克通配符SSL证书,一张通配型证书实现全站加密

      赛门铁克通配型SSL证书,验证域名所有权和企业信息,属于企业验证(OV) 级SSL证书,最高支持256位加密.申请通配符SSL证书可以保护相同主域名下无限数量的多个子域名(主机).例如,一个通配符 ...

  9. 全球数字高程数据(DEM)详解,还有地形晕渲、等高线等干货

    1 基本概念 DEM是数字高程模型的英文简称(Digital Elevation Model),是研究分析地形.流域.地物识别的重要原始资料.由于DEM 数据能够反映一定分辨率的局部地形特征,因此通过 ...

随机推荐

  1. 51Nod-1586-约数和

    #include <cstdio> using namespace std; typedef long long ll; ; int n, q; int cnt[MAXN]; ll a[M ...

  2. #学习方法2打印为空,说明#延迟加载#解决方案:将nameField等设置改在viewDidLoad中设置

    #学习方法#error调试#NSLog调试之无法进行数据传输,Edit无法现实之前编辑 的内容             https://www.evernote.com/shard/s227/sh/c ...

  3. js中typeof 与instanceof的区别

    1.typeof 用来检测给定变量的数据类型,其返回的值是下列某个字符串: "undefined":变量未定义 "boolean":变量为布尔类型 " ...

  4. [NOIP 2010] 引水入城

    搜索+贪心. 参考博客:http://blog.sina.com.cn/s/blog_8442ec3b0100xib1.html 主要是要看出来,如果有解的话,每个沿湖城市能够流到的范围是连续的区间. ...

  5. 6.shell判断语句

    [ condition ](注意condition前后要有空格),可以使用$?验证(0为true,>1为false) 两个整数的比较:=:字符串比较-lt:小于-gt:大于-le:小于等于-ge ...

  6. OleDbDataAdapter具体使用11

    using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...

  7. Selenium2+python自动化73-定位的坑:class属性有空格【转载】

    前言 有些class属性中间有空格,如果直接复制过来定位是会报错的InvalidSelectorException: Message: The given selector u-label f-dn ...

  8. CWnd创建WS_CHILD和WS_POPUP窗口的不同

    转载:http://blog.csdn.net/tangaowen/article/details/6054152 最近在写一个从CWnd派生出来的自绘窗口,以前在包装自己的类的Create函数都是这 ...

  9. Qt笔记——Event

    #ifndef MYBUTTON_H #define MYBUTTON_H #include <QPushButton> class MyButton : public QPushButt ...

  10. IOC(控制反转)的理解

    1.IOC的理论背景 我们知道在面向对象设计的软件系统中,它的底层都是由N个对象构成的,各个对象之间通过相互合作,最终实现系统地业务逻辑[1]. 图1 软件系统中耦合的对象 如果我们打开机械式手表的后 ...