写给高级前端的WebGL教程(03) 顶点缓冲区与绘制

246 阅读1分钟

api讲解

生成缓冲区对象

let buffer = context.createBuffer();

绑定缓冲区对象

context.bindBuffer(type, buffer);

添加数据

context.bufferData(type, new Float32Array(srcData), usage||context.STATIC_DRAW);

完整代码

class Buffer {

    constructor(context, type, srcData, usage) {
        let buffer = context.createBuffer();
        context.bindBuffer(type, buffer);
        context.bufferData(type, new Float32Array(srcData), usage || context.STATIC_DRAW);
        this.m_type = type;
        this.m_buffer = buffer;
        this.m_context = context;
    }
    bindBuffer() {
        this.m_context.bindBuffer(this.m_type, this.m_buffer);
    }

}

class ArrayBuffer extends Buffer {

    constructor(context, srcData, usage) {
        super(context, context.ARRAY_BUFFER, srcData, usage)
    }
}

绘制三角形

完整代码如下:

let a_position = 0;
let shaderProgram = new ShaderProgram(context,
    [createVertexShader(context, 
     `attribute vec3 a_position;
        void main(void){
            gl_Position = vec4(a_position, 1.0);
        }`), 
        createFragmentShader(context, 
        `void main(void){
            gl_FragColor = vec4(0.0, 1.0, 1.0, 1.0);
        }`)])
shaderProgram.bindAttribLocation(a_position, "a_position");
shaderProgram.useProgram();

let jsArrayData = [
    0.0, 1.0, 0.0,
    -1.0, -1.0, 0.0,
    1.0, -1.0, 0.0
];
let buffer = new ArrayBuffer(context, jsArrayData);
webgl.clearColor(0.0, 0.0, 0.0, 1.0);
webgl.clear(webgl.COLOR_BUFFER_BIT);
buffer.bindBuffer();
webgl.enableVertexAttribArray(a_position);
webgl.vertexAttribPointer(a_position, 3, webgl.FLOAT, false, 0, 0);
webgl.drawArrays(webgl.TRIANGLES, 0, 3);