WebGL Drawing Multiple Shapes of Different Colour

旧时模样 提交于 2019-12-02 12:40:51

What did you try? There's a lot of issues with that code and it gets errors trying to run it.

First off initShaders returns the shader on gl.program which makes zero sense. WebGL applications usually have multiple shader programs. Instead you want initShaders to return a program so you can do things like

var program1 = initShaders(gl, vertex1ShaderSource, fragment1ShaderSource);
var program2 = initShaders(gl, vertex2ShaderSource, fragment2ShaderSource);
var program3 = initShaders(gl, vertex3ShaderSource, fragment3ShaderSource);
..etc...

Next up initVertexBuffers references a variable called program but no such variable exists.

initVertexBuffers is setting uniforms but you want to set uniforms just before you start drawing, not when initializing vertices.

initVertexBuffers is also looking up attribute and uniform locations and checking for errors. On the one hand it's not bad to check for those kinds of errors per se but it makes your code harder to debug in other ways. In most WebGL programs, if you get no errors but something doesn't appear on the screen the first thing to do is make your fragment shader return a solid color

precision mediump float;
uniform vec4 u_FragColor;
void main() {
  //gl_FragColor = u_FragColor;
  gl_FragColor = vec4(1, 0, 0, 1); // return red
}

When you do that WebGL will optimize out the unsued u_FragColor and your code that's checking that you got the location for u_FragColor will fail making it impossible to debug your shaders.

I'd suggest reading some other tutorials on WebGL.

To draw multiple copies of the same shape the process is generally

At init time

 set up program
 look up attribute locations and uniform locations
 setup vertices for shape

At draw time

 setup attributes for shape
 gl.useProgram(program for shape)
 for each instance of shape
   set uniforms
     set a matrix uniform to position and orient the shape
     set a color uniform for the color
   drawArrays/drawElements

To draw multiple different shapes the process is usually

At init time

 set up programs
 look up attribute locations and uniform locations
 for each shape
   setup vertices for shape

At draw time

 for each shape
   gl.useProgram(program for shape) (if different from last shape)
   setup attributes for shape (if different from last shape)
   set uniforms
     set a matrix uniform to position and orient the shape
     set a color uniform for the color
   drawArrays/drawElements

As for matrices for positioning and orienting shapes see this article

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!