试图从vec4获取颜色数据时WebGL错误



我在WebGL中渲染正方形时遇到了一个问题。当我在Chrome中运行程序时,我得到错误:

GL ERROR :GL_INVALID_OPERATION : glDrawArrays: attempt to access out of range vertices in attribute 0

我认为这是因为,在某些时候,缓冲区在试图获取数据时正在查看错误的数组。我已经把问题定位到

gl.vertexAttribPointer(pColorIndex, 4, gl.FLOAT, false, 0, 0);
下面代码中的

行。例如,如果我将4更改为2,代码将运行,但不正确(因为我在这里查看颜色数据的vec4)。我的数组绑定方式有问题吗?

    bindColorDisplayShaders();
// clear the framebuffer
gl.clear(gl.COLOR_BUFFER_BIT);
// bind the shader
gl.useProgram(shader);
// set the value of the uniform variable in the shader
var shift_loc = gl.getUniformLocation(shader, "shift");
gl.uniform1f(shift_loc, .5);
// bind the buffer
gl.bindBuffer(gl.ARRAY_BUFFER, vertexbuffer);
// get the index for the a_Position attribute defined in the vertex shader
var positionIndex = gl.getAttribLocation(shader, 'a_Position');
if (positionIndex < 0) {
    console.log('Failed to get the storage location of a_Position');
    return;
}
// "enable" the a_position attribute
gl.enableVertexAttribArray(positionIndex);
// associate the data in the currently bound buffer with the a_position attribute
// (The '2' specifies there are 2 floats per vertex in the buffer.  Don't worry about
// the last three args just yet.)
gl.vertexAttribPointer(positionIndex, 2, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, null);
// bind the buffer with the color data
gl.bindBuffer(gl.ARRAY_BUFFER, chosencolorbuffer);
var pColorIndex = gl.getUniformLocation(shader, 'a_ChosenColor');
if(pColorIndex < 0){
    console.log('Failed to get the storage location of a_ChosenColor');
}
gl.enableVertexAttribArray(pColorIndex);
gl.vertexAttribPointer(pColorIndex, 4, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, null);
// draw, specifying the type of primitive to assemble from the vertices
gl.drawArrays(gl.TRIANGLES, 0, numPoints);

您只能使用uniform vertex attribute,这是两码事。

当使用顶点属性时,您必须匹配位置缓冲区中的顶点数量,并使用gl.getAttribLocation获得位置。

当使用统一你不是通过数组缓冲区提供它的数据,而是使用gl.uniform*方法来设置它们的值。

在您的示例中gl.uniform4fv(pColorIndex, yourColorVector) .

最新更新