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

    1
    <canvas id="myCanvas" width="600" height="300" style="border: 1px solid red"></canvas>
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    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);

      

    posted @   Rain Man  阅读(1413)  评论(0编辑  收藏  举报
    编辑推荐:
    · 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
    · .NET Core 中如何实现缓存的预热?
    · 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
    · AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
    · 基于Microsoft.Extensions.AI核心库实现RAG应用
    阅读排行:
    · 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
    · 地球OL攻略 —— 某应届生求职总结
    · 提示词工程——AI应用必不可少的技术
    · Open-Sora 2.0 重磅开源!
    · 字符编码:从基础到乱码解决
    点击右上角即可分享
    微信分享提示