simple example - attempt to access out of range vertices err


Hi Everyone,

I am getting the following error in a very simple example shown below:

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

<script id='vshader' type='x-shader'>
	attribute vec2 aVertexPosition;
	void main() {
		gl_Position = vec4(aVertexPosition, 0, 1);
<script id='fshader' type='x-shader'>
	precision mediump float;
	void main() {
		gl_FragColor = vec4(1, 0, 0, 1);

	var c = document.getElementById('cv');
	var gl = c.getContext('experimental-webgl');

	var vertexPosBuffer = gl.createBuffer();
	gl.bindBuffer(gl.ARRAY_BUFFER, vertexPosBuffer);
	var vertices = [-1, -1, 1, -1, -1, 1, 1, 1];
	gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
	vertexPosBuffer.itemSize = 2;
	vertexPosBuffer.numItems = 4;

	var vertexColorBuffer = gl.createBuffer();
	gl.bindBuffer(gl.ARRAY_BUFFER, vertexColorBuffer);  // adding this line causes the error
	var colors = [1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1];
//	gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);   // enabling this line removes the error but still nothing is rendered

	var vs = document.getElementById('vshader').textContent;
	var fs = document.getElementById('fshader').textContent;
	var program = createProgram(vs,fs);

	program.vertexPosAttrib = gl.getAttribLocation(program, 'aVertexPosition');
	gl.vertexAttribPointer(program.vertexPosAttrib, vertexPosBuffer.itemSize, gl.FLOAT, false, 0, 0);

	gl.drawArrays(gl.TRIANGLE_STRIP, 0, vertexPosBuffer.numItems);

There are no compile/link errors with the shaders.
Without color buffer related code I can see the red rectangle.
I am using Google Chrome, similar behaviour observed in Firefox.

Could someone please take a look and let me know what am I missing here?

best regards


You only setup your position buffer, then setup the color buffer, then your call to gl.vertexAttribPointer is using your color buffer (since that’s the last buffer bound) but you never init your color buffer (you have gl.bufferData for the color buffer commented out)

gl.vertexAttribPointer uses the buffer you last bound with gl.bindBuffer(gl.ARRAY_BUFFER, …)


Thanks Greggman, that helped to resolve the issue.



I meet the same error on Mac but it works in windows
here is my code:
gl.uniform1i(lineType, 1);
gl.bindBuffer(gl.ARRAY_BUFFER, lineBuf);
gl.vertexAttribPointer(linePosition, 2, gl.FLOAT, false, 0, 0);
gl.uniform4f(lineColor, 0.6,0.6,0.6,1.0);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
-1, 1,
1, 1,
1, -1,
-1, -1,
]), gl.STATIC_DRAW);
gl.drawArrays(gl.LINE_LOOP, 0, 4);
Could someone please take a look and let me know what am I missing here?


I resolved this issue
the reason of this error is :the counts of vertices is deferent between drawArrays(gl.TRIANGLE,) and drawArrays(gl.LINES,),cause the mac browser report WebGL error