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

<canvas ></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);

  

相关文章:

  • 2021-04-20
  • 2021-06-02
  • 2022-02-09
  • 2021-11-18
  • 2022-12-23
  • 2022-12-23
  • 2022-01-02
  • 2021-11-10
猜你喜欢
  • 2022-01-12
  • 2021-11-19
  • 2021-08-03
  • 2022-01-27
  • 2022-12-23
  • 2021-09-05
  • 2021-06-14
相关资源
相似解决方案