在 WebGL 中设置缓冲区数据

Setting buffer data in WebGL

我在调用 bindBuffer

之前尝试用数据填充缓冲区
const triangleBuffer = context.createBuffer();
// context.bindBuffer(context.ARRAY_BUFFER, triangleBuffer);
context.bufferData(context.ARRAY_BUFFER, triangleVertices, context.STATIC_DRAW);

然后我得到一个错误:

WebGL: INVALID_OPERATION: bufferData: no buffer

我在第一行创建了缓冲区,但我不明白为什么我不能用数据填充它。

我不能在绑定到 context.ARRAY_BUFFER 之前填充创建的缓冲区吗?这种行为有什么原因吗?

ARRAY_BUFFER 是一个内部 WebGL 变量(或者说它是一个内部 WebGL 变量的 id)

有效地像这样工作

context = {
  ARRAY_BUFFER: 34962,  // this is an enum value

  arrayBufferBinding: null,

  bindBuffer(target, buffer) {
    if (target === this.ARRAY_BUFFER) {
      this.arrayBufferBinding = buffer;
    }
    ...
  },

  bufferData(target, data, hint) {
    let buffer;
    if (target === this.ARRAY_BUFFER) {
      buffer = this.arrayBufferBinding;
    }
    ...
    setDataOnBuffer(buffer, data, hint);
  },
};

所以你必须绑定缓冲区。 WebGL 不直接在大多数 WebGL 对象(缓冲区、纹理、渲染缓冲区、帧缓冲区、顶点数组)上设置状态。您必须绑定对象,然后根据绑定的位置引用它。

this and this and