WebGL基础(二)

你可能知道,构成三维模型的基本单位都是三角形,不管三维图形的形状多么复杂,其基本组成部分都是三角形,所以学习三角形的绘制很是重要,所以本节主要是讲解一下三角形的绘制。
先上程序和结果

// HelloTriangle.js (c) 2012 matsuda
// 顶点着色器
var VSHADER_SOURCE =
  'attribute vec4 a_Position;\n' +
  'void main() {\n' +
  '  gl_Position = a_Position;\n' +
  '}\n';

// 片元着色器
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');

  // 获取上下文
  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 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);

  // 绘制三角形
  gl.drawArrays(gl.TRIANGLES, 0, n);
}

function initVertexBuffers(gl) {
  var vertices = new Float32Array([
    0, 0.5,   -0.5, -0.5,   0.5, -0.5
  ]);
  var n = 3; //点的个数

  // 创建缓冲区对象
  var vertexBuffer = gl.createBuffer();
  if (!vertexBuffer) {
    console.log('Failed to create the buffer object');
    return -1;
  }

  //绑定缓冲区到目标
  gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
  // 写入数据
  gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);

  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, 2, gl.FLOAT, false, 0, 0);

  // 连接a_Position 变量和分配给它的缓冲对象
  gl.enableVertexAttribArray(a_Position);

  return n;
}
三角形

首先,绘制多个点使用了缓冲区对象,这是WebGL的一种很方便的机制,它可以一次性的想着色器传入多个顶点的数据,然后将这些数据保存在其中,供顶点着色器使用。机制如下:


缓冲器机制

主要步骤如下:
1、创建缓冲器对象(gl.createBuffer());
2、绑定缓冲区对象( gl.bindBuffer());
3、将数据写入缓冲区对象(gl.bufferData());
4、将缓冲区对象分配给一个attribute变量( gl.vertexAttribPointe()));
5、开启attribute变量( gl.enableVertexAttribArray());


gl.createBuffer()

gl.bindBuffer()

gl.bufferData()

gl.vertexAttribPointe()

gl.enableVertexAttribArray()

创建好缓冲器对象后,就可以使用 gl.drawArrays(gl.TRIANGLES, 0, n);绘制三角形了。


gl.drawArrays

gl.drawArrays可以绘制的图像有


可绘制的图形
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容