You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 20:40:29