WebGLRenderingContext.enableVertexAttribArray()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年7月.
在 WebGL API 中,使用 WebGLRenderingContext 中的 enableVertexAttribArray() 方法,可以打开属性数组列表中指定索引处的通用顶点属性数组。
备注:
你可以通过以下方法关闭顶点属性数组 disableVertexAttribArray().
在 WebGL 中,作用于顶点的数据会先储存在attributes。这些数据仅对 JavaScript 代码和顶点着色器可用。属性由索引号引用到 GPU 维护的属性列表中。在不同的平台或 GPU 上,某些顶点属性索引可能具有预定义的值。创建属性时,WebGL 层会分配其他属性。
无论怎样,都需要你使用 enableVertexAttribArray() 方法,来激活每一个属性以便使用,不被激活的属性是不会被使用的。一旦激活,以下其他方法就可以获取到属性的值了,包括vertexAttribPointer()、vertexAttrib*() 和 getVertexAttrib()。
语法
enableVertexAttribArray(index)
参数
index-
类型为
GLuint的索引,指向要激活的顶点属性。如果你只知道属性的名称,不知道索引,你可以使用以下方法来获取索引getAttribLocation().
返回值
无(undefined)。
错误
你可以使用getError()方法,来检查使用enableVertexAttribArray()时发生的错误。
WebGLRenderingContext.INVALID_VALUE-
非法的
index。一般是index大于或等于了顶点属性列表允许的最大值。该值可以通过WebGLRenderingContext.MAX_VERTEX_ATTRIBS获取。
例子
该例子是 A basic 2D WebGL animation example 中的一部分,用以说明 enableVertexArray() 是如何激活顶点属性,并将顶点数据传输到 shader 函数的。
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
aVertexPosition = gl.getAttribLocation(shaderProgram, "aVertexPosition");
gl.enableVertexAttribArray(aVertexPosition);
gl.vertexAttribPointer(
aVertexPosition,
vertexNumComponents,
gl.FLOAT,
false,
0,
0,
);
gl.drawArrays(gl.TRIANGLES, 0, vertexCount);
该段代码来自于 "A basic 2D WebGL animation example." 中的 the function animateScene() 。通过连接来查看全文,你可以查看产生的动画效果。
以上代码中,使用了bindBuffer()来设置将用于绘图的顶点数据的缓存。然后使用getAttribLocation()来获取顶点数据在 shader 函数中的索引。
我们用 enableVertexAttribArray() 函数来激活 aVertexPosition中记录的索引位置,以便在后面对该顶点属性进行数据绑定。
使用vertexAttribPointer() 将缓存数据绑定到 shader 函数中的顶点属性。于是,我们可以通过drawArrays()函数将顶点一一绘制。
Specifications
| Specification |
|---|
| WebGL Specification> # 5.14.10> |
Browser compatibility
Loading…