编程语言
首页 > 编程语言> > WebGL编程指南入门基础篇

WebGL编程指南入门基础篇

作者:互联网

WebGL编程指南笔记-入门基础篇

着色器介绍

着色器分为顶点着色器片元着色器

从js文件到浏览器渲染结果的处理流程示意图
2019-04-28-15-13-28

画点

// HelloPoint1.js (c) 2012 matsuda
// Vertex shader program
var VSHADER_SOURCE = 
  'void main() {\n' +
  '  gl_Position = vec4(0.0, 0.0, 0.0, 1.0);\n' + // Set the vertex coordinates of the point
  '  gl_PointSize = 10.0;\n' +                    // Set the point size
  '}\n';

  
// Fragment shader program
var FSHADER_SOURCE =
  'void main() {\n' +
  '  gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\n' + // Set the point color
  '}\n';
  
// Initialize shaders
  if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
    console.log('Failed to intialize shaders.');
    return;
  }
  
// Draw a point
  gl.drawArrays(gl.POINTS, 0, 1);

webgl初始化流程

/**
 * Create a program object and make current
 * @param gl GL context
 * @param vshader a vertex shader program (string)
 * @param fshader a fragment shader program (string)
 * @return true, if the program object was created and successfully made current 
 */
function initShaders(gl, vshader, fshader) {
  var program = createProgram(gl, vshader, fshader);
  if (!program) {
    console.log('Failed to create program');
    return false;
  }

  gl.useProgram(program);
  gl.program = program;

  return true;
}

2019-04-28-15-32-12

齐次坐标

homogeneous coordinate

2019-04-28-15-44-45

传输变量

所有 attribute 变量都以 a_前缀开始; 所有 uniform 变量都以u_ 前缀开始

var a_Position = gl.getAttribLocation(gl.program, 'a_Position'); 
  gl.vertexAttrib1f(location, v0)   
  gl.vertexAttrib2f(location, v0, v1)   
  gl.vertexAttrib3f(location, v0, v1, v2)   
  gl.vertexAttrib4f(location, v0, v1, v2, v3) 

2019-04-28-16-22-10

 gl.getUniformLocation(program, name)   
  gl.uniform1f(location, v0)   
  gl.uniform2f(location, v0, v1)   
  gl.uniform3f(location, v0, v1, v2)   
  gl.uniform4f(location, v0, v1, v2, v3)   

绘制和变换三角形

使用缓冲区对象

    1.    创建缓冲区对象:Create a buffer object ( gl.createBuffer() ).   
    2.    将缓冲区对象绑定到目标:Bind the buffer object to a target ( gl.bindBuffer() ).   
    3.    向缓冲区对象中写入数据:Write data into the buffer object ( gl.bufferData() ).   
    4.    将缓冲区对象分配给a_Position变量:Assign the buffer object to an attribute variable ( gl.vertexAttribPointer() ).   
    5.    连接a_Position变量与分配给它的缓冲区对象:Enable assignment ( gl.enableVertexAttribArray() ).    

2019-04-28-17-10-54

webgl绘制基本图形

2019-04-28-17-35-26

2019-04-28-17-38-03

移动、旋转和缩放

 x' = x cos β – y sin β  
 y' = x sin β + y cos β  
 z' = z     

旋转平移矩阵
2019-04-28-18-17-26

高级变换与动画基础

矩阵操作函数库

2019-04-28-19-16-01

颜色与纹理

将非坐标数据传入顶点着色器

多种顶点数据信息存入顶点着色器

顶点着色器和片元着色器之间的数据传输

纹理映射

texture mapping

纹理映射过程主要包括五个部分

标签:入门,WebGL,编程,纹理,program,片元,缓冲区,gl,着色器
来源: https://blog.csdn.net/austindev/article/details/89646980