studyNotes icon indicating copy to clipboard operation
studyNotes copied to clipboard

WebGL学习笔记

Open junhey opened this issue 8 years ago • 0 comments

利用canvas和javascript,就可以在页面绘制2d图像,但对于3d的图像,目前是无能为力的。要绘制3d图像,就必须使用WebGL。 以我的理解,WebGL是内嵌在浏览器中,在使用时是通过javascript调用浏览器提供的WebGL API,然后在canvas绘图区绘制图像。 下面是简单的WebGL例子

<!DOCTYPE html>
<html lang='zh-cmn-Hans'>
<head>
<meta charset='utf-8' />
<title>Canvas - WebGL</title>
</head>
<body>
<h1>HTML5 - Canvas - WebGL</h1>
<canvas id='glcanvas' width='500' height='500'></canvas>
<script type="text/javascript">
window.onload = function(){
    init();
}
function init() {
    var canvas, gl;
    canvas = document.getElementById('glcanvas');
    gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl'); //获取WebGL绘图上下文
    if (!gl) {
        console.log('不支持WebGL!');
        return;
    }
    gl.clearColor(0.0, 0.0, 0.0, 1.0); //设置背景色
    gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT); //清空绘图区
}
</script>
</body>
</html>

WebGL使用着色器信息绘图,着色器使用OpenGL ES(GLSL)编写

着色器分为顶点着色器(Vertex shader)和片元着色器(Fragment shader),顶点着色器描述位置信息,片元着色器描述颜色信息。

//顶点着色器
void main(){
    gl_Position = vec4(0.0, 0.0, 0.0, 1.0);
    gl_PointSize = 10.0;
}
//片元着色器
void main(){
    gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}

gl_Position、gl_PointSize、gl_FragColor均为GLSL内置变量名。 vec4描述了数据类型为4个浮点数,相应的vec1表示1个浮点数,vec2表示2个浮点数,vec3表示3个浮点数,在gl_Position中的4个数值中,前3个应该是三维坐标的x、y、z,目前还不太明白最后一个数值的意义,有了着色器信息后,就可以使用这些信息开始绘制了。 下面给出绘制三个点的具体代码

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Draw Multiple Points</title>
  </head>

  <body onload="main()">
    <canvas id="webgl" width="400" height="400">
    Please use a browser that supports "canvas"
    </canvas>

    <script src="../lib/webgl-utils.js"></script>
    <script src="../lib/webgl-debug.js"></script>
    <script src="../lib/cuon-utils.js"></script>
    <script src="MultiPoint.js"></script>
  </body>
</html>
// Vertex shader program
var VSHADER_SOURCE =
  'attribute vec4 a_Position;\n' +
  'void main() {\n' +
  '  gl_Position = a_Position;\n' +
  '  gl_PointSize = 10.0;\n' +
  '}\n';

// Fragment shader program
var FSHADER_SOURCE =
  'void main() {\n' +
  '  gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\n' +
  '}\n';

function main() {
  // Retrieve <canvas> element
  var canvas = document.getElementById('webgl');

  // 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;
  }

  // Write the positions of vertices to a vertex shader
  var n = initVertexBuffers(gl);
  if (n < 0) {
    console.log('Failed to set the positions of the vertices');
    return;
  }

  // Specify the color for clearing <canvas>
  gl.clearColor(0, 0, 0, 1);

  // Clear <canvas>
  gl.clear(gl.COLOR_BUFFER_BIT);

  // Draw three points
  gl.drawArrays(gl.POINTS, 0, n);
}

function initVertexBuffers(gl) {
  var vertices = new Float32Array([
    0.0, 0.5,   -0.5, -0.5,   0.5, -0.5
  ]);
  var n = 3; // The number of vertices

  // Create a buffer object
  var vertexBuffer = gl.createBuffer();
  if (!vertexBuffer) {
    console.log('Failed to create the buffer object');
    return -1;
  }

  // Bind the buffer object to target
  gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
  // Write date into the buffer object
  gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);

  var a_Position = gl.getAttribLocation(gl.program, 'a_Position');
  console.log("a_Position",)
  if (a_Position < 0) {
    console.log('Failed to get the storage location of a_Position');
    return -1;
  }
  // Assign the buffer object to a_Position variable
  gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0);

  // Enable the assignment to a_Position variable
  gl.enableVertexAttribArray(a_Position);

  return n;
}

attribute变量用于与顶点相关的数据,uniform变量用于与顶点无关的数据。书上是这么写,但理解起来很别扭。我的理解是在3D绘图中,每个点的坐标都会经过坐标变换最后映射到2D画布上,这时点的坐标是经过变换后的坐标,那么这个坐标信息就要使用attribute变量,而不管怎么变换,点的颜色都是不变的,所以颜色信息使用uniform变量。

参考:

WebGL教程
学习WebGL 一篇文章理清WebGL绘制流程 WebGL 技术储备指南
图解WebGL&Three.js工作原理 WebGL 中文教程-w3c school

junhey avatar Jun 12 '18 09:06 junhey