WebGL:INVALID_OPERATION:vertexAttribPointer:步幅或偏移量对类型无效

WebGL: INVALID_OPERATION: vertexAttribPointer: stride or offset not valid for type

我学习 WebGL。

当我尝试绘制三个点时出现一些错误,每个点都有自己的位置、大小和颜色。我尝试通过相同的缓冲区来完成。

// To draw three points. Each of this has own location, size and color.
function start(gl){
  if(!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)){
    console.log('Failes shaders initialization.');
    return;
  }
  var a_Position = gl.getAttribLocation(gl.program, 'a_Position');
  if(a_Position < 0){
    console.log('The "a_Position" variable was not found in the shader code.');
    return;
  }
  var a_PointSize = gl.getAttribLocation(gl.program, 'a_PointSize');
  if(a_PointSize < 0){
    console.log('The "a_PointSize" variable was not found in the shader code.');
    return;
  }

  var a_FragColor = gl.getAttribLocation(gl.program, 'a_FragColor');
  if(a_FragColor < 0){
    console.log('The "a_FragColor" variable was not found in the shader code.');
    return;
  }

  var data = new Float32Array([
     // a_Position, a_PointSize and a_FragColor in the each record:
    -0.25, -0.25, 10.0, 1.0, 0.0, 0.0, 1.0,
     0.00,  0.25, 20.0, 0.0, 1.0, 0.0, 1.0,
     0.25, -0.25, 30.0, 0.0, 0.0, 1.0, 1.0
  ]);

  var buffer = gl.createBuffer();
  if(!buffer){
    console.log('Can not create a buffer.');
    return;
  }
  gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);

  var FSIZE = data.BYTES_PER_ELEMENT;  
  var RECORDSIZE = 7;

  gl.vertexAttribPointer(a_Position,  2, gl.FLOAT, false, FSIZE * RECORDSIZE, 0);
  gl.vertexAttribPointer(a_PointSize, 1, gl.FLOAT, false, FSIZE * RECORDSIZE, 2);
  gl.vertexAttribPointer(a_FragColor, 4, gl.FLOAT, false, FSIZE * RECORDSIZE, 3);

  gl.enableVertexAttribArray(a_Position);
  gl.enableVertexAttribArray(a_PointSize);
  gl.enableVertexAttribArray(a_FragColor);

  gl.clearColor(0.0,0.0,0.0,1.0);
  gl.clear(gl.COLOR_BUFFER_BIT);

  gl.drawArrays(gl.POINTS, 0, 3);
}

但是我遇到了一些错误:

我不清楚。我做错了什么?

documentation 中所写,抛出 INVALID_OPERATION:

  • 如果 stride 或 offset 不是类型的倍数。

由于您使用 GL_FLOAT 作为大小为 4 字节的类型,因此偏移量只允许是 4 的倍数。在此代码中使用的 2 和 3 不是。

                                                                           ||
                                                                           \/
gl.vertexAttribPointer(a_PointSize, 1, gl.FLOAT, false, FSIZE * RECORDSIZE, 2);
gl.vertexAttribPointer(a_FragColor, 4, gl.FLOAT, false, FSIZE * RECORDSIZE, 3);