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

WebGL示例中texcoord的使用疑问:传递至片元着色器后为何未被利用?

WebGL中texcoord的使用疑问

texcoord在创建点网格时的定义如下:

const u0 = x / cellsAcross;
const v0 = z / cellsDeep;
const u1 = (x + 1) / cellsAcross;
const v1 = (z + 1) / cellsDeep;

随后通过顶点着色器传递texcoord:

attribute vec4 position;
attribute vec3 normal;
attribute vec2 texcoord;

uniform mat4 projection;
uniform mat4 modelView;

varying vec3 v_normal;
varying vec2 v_texcoord;

void main() {
  gl_Position = projection * modelView * position;
  v_normal = mat3(modelView) * normal;
  v_texcoord = texcoord;
}

最终传入片元着色器的代码:

precision highp float;

varying vec3 v_normal;
varying vec2 v_texcoord;
varying float v_modelId;

void main() {
  vec3 lightDirection = normalize(vec3(1, 2, -3));  // 任意光照方向

  float l = dot(lightDirection, normalize(v_normal)) * .5 + .5;
  gl_FragColor = vec4(vec3(0,1,0) * l, 1);
}

你的理解完全正确,这段片元着色器里确实没有使用传递过来的v_texcoord变量——它只是被声明为varying变量,但在实际的颜色计算逻辑中没有被引用。

你后续可以编写代码将其用于纹理采样,比如添加纹理采样器uniform,通过texture2D函数使用v_texcoord获取纹理颜色,替换当前的固定绿色输出逻辑。

内容的提问来源于stack exchange,提问作者Robert Calfee

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 08:25:15