WebGL逐顶点设置vec4颜色无渲染问题排查
问题:WebGL为顶点单独设置颜色时无渲染内容
我希望为每个顶点单独设置颜色,以下是使用的着色器代码:
const VERTEX_SHADER_SOURCE = ` precision mediump float; attribute vec3 aPosition; attribute vec4 aColor; varying vec4 vColor; uniform mat4 uMatrix; void main() { vColor = aColor; gl_Position = uMatrix * vec4(aPosition, 1); } ` const FRAGMENT_SHADER_SOURCE = ` precision mediump float; varying vec4 vColor; void main() { gl_FragColor = vColor;}`
使用上述代码时,画面无任何渲染内容,对应的WebGL缓冲区配置代码如下:
const attrLocations = { position: gl.getAttribLocation(this.#program, 'aPosition'), color: gl.getAttribLocation(this.#program, 'aColor') } gl.bindBuffer(gl.ARRAY_BUFFER, this.#vertexBuffer) gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(this.#sphere.getVertices()), gl.STATIC_DRAW) gl.vertexAttribPointer(attrLocations.position, 3, gl.FLOAT, false, 0, 0) gl.enableVertexAttribArray(attrLocations.position) gl.bindBuffer(gl.ARRAY_BUFFER, this.#colorBuffer) gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(this.#drawMode.getColors.call()), gl.STATIC_DRAW) gl.vertexAttribPointer(attrLocations.color, 4, gl.FLOAT, false, 0 , 0) gl.enableVertexAttribArray(attrLocations.color) gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.#indicesBuffer) gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(this.#drawMode.getIndices.call()), gl.STATIC_DRAW)
同时观察到以下现象:
- 若将片段着色器修改为
gl_FragColor = vec4(1, 0, 0, 1);,物体可正常渲染并显示指定颜色 - 若将
gl.vertexAttribPointer(attrLocations.color, 4, gl.FLOAT, false, 0 , 0)中的4改为3,物体可渲染但颜色明显错误 - 已确认
this.#sphere.getVertices().length / 3 === this.#drawMode.getColors.call().length / 4结果为true,即每个vec3顶点对应一个vec4颜色(例如100个顶点对应长度为300的顶点数组和长度为400的颜色数组)
请问该问题的原因是什么?
内容的提问来源于stack exchange,提问作者Dmitry
相关产品推荐
相关产品推荐

