添加EBO

47 阅读1分钟
import initShaders from './initShaders.js'

let canvas = document.getElementById('webgl')
let gl = canvas.getContext('webgl2')

let vertexShader = `#version 300 es

layout (location = 0) in vec3 a_position;
layout (location = 1) in vec3 a_color;
out vec3 v_color;

void main() {
    v_color = a_color;
    gl_Position = vec4(a_position, 1.0);
    gl_PointSize = 10.0;
}
`

let fragmentShader = `#version 300 es 

precision mediump float;
uniform float u_w;
uniform float u_h;

in vec3 v_color;
out vec4 fragColor;
// gl_FragCoord: canvas画布的坐标(100, 100)
void main() {
    fragColor = vec4(gl_FragCoord.x / u_w, gl_FragCoord.y / u_h, 0.0, 1.0);
}
`
initShaders(gl, vertexShader, fragmentShader)

let canvas_w = 200, canvas_h = 200
let u_w = gl.getUniformLocation(gl.program, 'u_w')
let u_h = gl.getUniformLocation(gl.program, 'u_h')
gl.uniform1f(u_w, canvas_w)
gl.uniform1f(u_h, canvas_h)
let vao;
initVertexBuffers(gl)

function initVertexBuffers(gl) {
    //4个点的坐标信息
       let positions = new Float32Array([
       -0.5, 0.5, 0.0, 
       -0.5, -0.5, 0.0, 
       0.5, -0.5, 0.0, 
       0.5, 0.5, 0.0, 
   ])


    //4个点的颜色信息
    let colors = new Float32Array([
        1.0, 0.0, 0.0,
        0.0, 1.0, 0.0,
        0.0, 0.0, 1.0,
        1.0, 1.0, 1.0,
    ])
    let indices = new Uint16Array([
        0, 1, 2, 0,2,3 // Front face
    ]);
    let FSIZE = positions.BYTES_PER_ELEMENT // Float32 Size = 4
   // 创建并绑定位置缓冲区
   const posVbo = gl.createBuffer();
   gl.bindBuffer(gl.ARRAY_BUFFER, posVbo);
   gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW);

   const colorVbo = gl.createBuffer();
   gl.bindBuffer(gl.ARRAY_BUFFER, colorVbo);
   gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW); 
   // 创建vao
    vao = gl.createVertexArray();
   gl.bindVertexArray(vao)

   gl.bindBuffer(gl.ARRAY_BUFFER, posVbo);//只有绑定了posVbo,下面的属性描述才会与此vbo相关
   gl.enableVertexAttribArray(0);
   gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 0, 0)

   gl.bindBuffer(gl.ARRAY_BUFFER, colorVbo);
   gl.enableVertexAttribArray(1);
   gl.vertexAttribPointer(1, 3, gl.FLOAT, false, 0, 0);
    
    // 5.ebo
    const ebo = gl.createBuffer();
    gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,ebo);
    gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,indices,gl.STATIC_DRAW);
    gl.bindBuffer(gl.ARRAY_BUFFER,null); 
    // 解绑vao
    gl.bindVertexArray(null);
}

draw(gl)

function draw(gl) {
    gl.clearColor(0.0, 0.0, 0.0, 1.0)
    gl.clear(gl.COLOR_BUFFER_BIT)
    // 绑定vao
    gl.bindVertexArray(vao)
    gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0)
}