【发布时间】:2022-10-15 11:05:42
【问题描述】:
我想分别为每个顶点设置颜色。这是着色器的代码:
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;
}`
使用此代码注意绘制:
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)
至
gl.vertexAttribPointer(attrLocations.color, 3, gl.FLOAT, false, 0 , 0)
(4 => 3),然后绘制对象(但显然颜色错误)。
但是this.#sphere.getVertices().length / 3 === this.#drawMode.getColors.call().length / 4 是true,所以每个 vec3 顶点都有 vec4 颜色。例如,有100 个顶点,所以会有长度为的顶点数组=300和颜色数组长度 =400.
那么,问题出在哪里?
【问题讨论】:
-
你用混合吗?颜色的 Alpha 通道是什么?
-
作为一个关于 Web 代码的问题,将其转换为可运行的 sn-p 将是一个好主意。 (甚至两个)
-
@Rabbid76 我不知道什么是混合,所以可能不使用它。颜色 alpha 可以是 1 或 0.9
标签: javascript webgl