【问题标题】:WebGL - which API to use?WebGL - 使用哪个 API?
【发布时间】:2014-06-03 03:33:42
【问题描述】:

我想绘制多个多边形形状(每个形状都有自己的一组顶点)。 我希望能够相互独立地定位这些形状。

我可以使用哪个 API 来设置顶点着色器的 a_Position?

  • A) gl.vertexAttrib3f
  • B) gl.vertexAttribPointer + gl.enableVertexAttribArray

谢谢。

【问题讨论】:

    标签: opengl-es webgl vertex-array vertex-attributes


    【解决方案1】:

    您的问题听起来像是您对 WebGL 真的很陌生?也许你应该read some tutorials?但在回答您的问题时:

    gl.vertexAttrib3f 仅允许您为 GLSL 属性提供单个常量值,因此您需要使用 gl.vertexAttribPointergl.enableVertexAttribArray。您还需要使用顶点数据设置缓冲区。

    gl.vertexAttrib3f 唯一的一点可以说是让你传入一个常量,以防你有一个使用多个属性的着色器,但你没有所有属性的数据。例如,假设您有一个同时使用纹理的着色器,因此需要纹理坐标,并且它还具有顶点颜色。像这样的

    顶点着色器

    attribute vec4 a_position;
    attribute vec2 a_texcoord;
    attribute vec4 a_color;
    
    varying vec2 v_texcoord;
    varying vec4 v_color;
    
    uniform mat4 u_matrix;
    
    void main() {
      gl_Position = u_matrix * a_position;
    
      // pass texcoord and vertex colors to fragment shader
      v_texcoord = a_texcoord;
      v_color = v_color;
    }
    

    片段着色器

    precision mediump float;
    
    varying vec2 v_texcoord;
    varying vec4 v_color;
    
    uniform sampler2D u_texture;
    
    void main() {
       vec4 textureColor = texture2D(u_texture, v_texcoord);
    
       // multiply the texture color by the vertex color
       gl_FragColor = textureColor * v_color;
    }
    

    此着色器需要顶点颜色。如果您的几何图形没有顶点颜色,那么您有 2 个选项 (1) 使用不同的着色器 (2) 关闭顶点颜色的属性并将其设置为恒定颜色,可能是白色。

    gl.disableVertexAttribArray(aColorLocation);
    gl.vertexAttrib4f(aColorLocation, 1, 1, 1, 1);
    

    现在即使没有顶点颜色数据,您也可以使用相同的着色器。

    同样,如果您没有纹理坐标,您可以传入一个白色的 1 像素着色器并将纹理坐标设置为某个常数。

    gl.displayVertexAttribArray(aTexcoordLocation);
    gl.vertexAttrib2f(aTexcoordLocation, 0, 0); 
    
    gl.bindTexture(gl.TEXTURE_2D, some1x1PixelWhiteTexture);
    

    在这种情况下,您还可以通过设置顶点颜色属性来决定使用什么颜色绘制。

    gl.vertexAttrib4f(aColorLocation, 1, 0, 1, 1);  // draw in magenta
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-11
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-22
      • 2016-09-28
      相关资源
      最近更新 更多