WebGLRenderingContext.enableVertexAttribArray()
在WebGL API中,使用 WebGLRenderingContext
中的enableVertexAttribArray()
方法,可以打开属性数组列表中指定索引处的通用顶点属性数组。
你可以通过以下方法关闭顶点属性数组 disableVertexAttribArray()
(en-US).
在WebGL中,作用于顶点的数据会先储存在attributes。这些数据仅对JavaScript代码和顶点着色器可用。属性由索引号引用到GPU维护的属性列表中。在不同的平台或GPU上,某些顶点属性索引可能具有预定义的值。创建属性时,WebGL层会分配其他属性。
无论怎样,都需要你使用enableVertexAttribArray()
方法,来激活每一个属性以便使用,不被激活的属性是不会被使用的。一旦激活,以下其他方法就可以获取到属性的值了,包括vertexAttribPointer()
,vertexAttrib*()
,和 getVertexAttrib()
(en-US)。
语法
void gl.enableVertexAttribArray(index);
参数
index
- 类型为
GLuint
(en-US) 的索引,指向要激活的顶点属性。如果您只知道属性的名称,不知道索引,您可以使用以下方法来获取索引getAttribLocation()
.
返回值
undefined
.
错误
您可以使用getError()
(en-US)方法,来检查使用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);
animateScene()
。 通过连接来查看全文,您可以查看产生的动画效果。以上代码中,使用了bindBuffer()
来设置将用于绘图的顶点数据的缓存。然后使用getAttribLocation()
来获取顶点数据在shader函数中的索引。
我们用 enableVertexAttribArray()
函数来激活 aVertexPosition
中记录的索引位置,以便在后面对该顶点属性进行数据绑定。
使用vertexAttribPointer()
将缓存数据绑定到shader函数中的顶点属性。于是,我们可以通过drawArrays()
函数将顶点一一绘制。
Specifications
Specification | Status | Comment |
---|---|---|
WebGL 1.0 enableVertexAttribArray |
Recommendation | Initial definition. |
OpenGL ES 2.0 glEnableVertexAttribArray |
Standard | Man page of the OpenGL API. |
Browser compatibility
BCD tables only load in the browser