WebGL在Blazor Server应用中渲染纹理为灰度的问题求助
问题根因
纹理渲染为灰度的核心原因是纹理创建时错误使用了单通道灰度像素格式,出现在BuildLandAsync方法的TexImage2DAsync调用参数中:
你当前传入的PixelFormat.LUMINANCE是WebGL定义的单通道灰度格式,只会读取像素的亮度值,直接丢弃彩色通道信息,无论输入数组是否包含RGB数据,最终都会被解析为灰度值。
修复方案
- 先确认你从
ArtworkProvider.GetStaticAsync返回的int数组的像素存储规则:- 若为3通道RGB排列,使用
PixelFormat.RGB作为格式参数 - 若为4通道RGBA排列,使用
PixelFormat.RGBA作为格式参数
- 若为3通道RGB排列,使用
- 修改
BuildLandAsync中的纹理创建代码,示例(RGBA格式):
public static async Task<Texture> BuildLandAsync(WebGLContext gl, int[] buffer, int width = 44, int height = 44) { var texture = await gl.CreateTextureAsync(); await gl.BindTextureAsync(TextureType.TEXTURE_2D, texture); // 只需要修改这一行的两个PixelFormat参数即可,根据你的实际像素格式调整 await gl.TexImage2DAsync(Texture2DType.TEXTURE_2D, 0, PixelFormat.RGBA, width, height, 0, PixelFormat.RGBA, PixelType.UNSIGNED_BYTE, buffer); await gl.TexParameterAsync(TextureType.TEXTURE_2D, TextureParameter.TEXTURE_MIN_FILTER, (int)TextureParameterValue.NEAREST); await gl.TexParameterAsync(TextureType.TEXTURE_2D, TextureParameter.TEXTURE_MAG_FILTER, (int)TextureParameterValue.NEAREST); await gl.TexParameterAsync(TextureType.TEXTURE_2D, TextureParameter.TEXTURE_WRAP_S, (int)TextureParameterValue.CLAMP_TO_EDGE); await gl.TexParameterAsync(TextureType.TEXTURE_2D, TextureParameter.TEXTURE_WRAP_T, (int)TextureParameterValue.CLAMP_TO_EDGE); return new Texture(gl, texture, width, height); }
校验注意事项
- 确认像素数组长度匹配:4444分辨率下,RGBA格式数组长度应为44444,RGB格式为4444*3,长度不匹配会额外引发渲染错乱
- 你的顶点、片元着色器逻辑无问题,不需要修改
内容的提问来源于stack exchange,提问作者3HMonkey
相关产品推荐
相关产品推荐

