WebGL编程笔记2:uniform变量使用

<canvas id="myCanvas" width="600" height="300" style="border: 1px solid red"></canvas>
const vertex = `
    precision lowp float;
    attribute vec3 vertexPosition;
    void main(void) {
        gl_Position = vec4(vertexPosition, 1.0);
    }
`;
const fragment = `
    precision lowp float;
    uniform   vec4 color;
    void main(void) {        
        gl_FragColor = color;
    }
`;

let canvas = document.getElementById('myCanvas');
let webgl = canvas.getContext('webgl');
const data_position = new Float32Array([
   // x       y      z        r       g       b       a
    -0.5,    0.5,    0.0,    0.9,    0.0,    0.0,    1.0,
    +0.5,    0.5,    0.0,    0.0,    0.8,    0.0,    1.0,
    +0.5,   -0.5,    0.0,    0.0,    0.0,    1.0,    1.0,
    -0.5,   -0.5,    0.0,    1.0,    1.0,    1.0,    1.0
]);
const data_index = new Uint16Array([
    0, 1, 2,
    0, 2, 3
]);
const FSIZE = data_position.BYTES_PER_ELEMENT;

webgl.clearColor(0, 1, 0, 1);
webgl.clear(webgl.COLOR_BUFFER_BIT);

// 第一步:编译Shader程序,并创建program
let program = createProgram(webgl, vertex, fragment);

// 第二步:创建数据缓冲区和索引缓冲区
let buffer_position = bindBufferWidthData(webgl, webgl.ARRAY_BUFFER, data_position);    // 将顶点数据写入数据缓冲区并启用
let buffer_index = bindBufferWidthData(webgl, webgl.ELEMENT_ARRAY_BUFFER, data_index);  // 将索引数据写入冲区并启用

// 第三步: 未Shader中的输入变量定义指针的,并分配取数位置
let vertexPosition = bindVertexAttributePointer(webgl, program, "vertexPosition", 3, webgl.FLOAT, false, FSIZE * 7, 0); // 每次从buffer中取28个字节,从这一段字节中的offset=0字节开始取3个浮点数

// 设置全局变量color
let color = webgl.getUniformLocation(program, 'color');
webgl.uniform4f(color, 1, 0, 0, 1);     // r g b a

// 开始绘制
webgl.drawElements(webgl.TRIANGLES, 6, webgl.UNSIGNED_SHORT, 0);

  

原文地址:https://www.cnblogs.com/rainman/p/12582133.html