我在WebGL中进行图像渲染时遇到问题:我有一个 Canvas ,其中一个四边形占据了整个 Canvas ,还有一个应该映射到整个四边形上的纹理(我已经设置了正确的纹理坐标)。
图像是包含RGB数据(按此顺序)的Uint8array,图像为1024 * 768像素。我有正确的缓冲区。这是图像的链接。
问题如下:当渲染到WebGL中时,即使我的 Canvas 大小等于图像大小,我的图片也变得模糊不清。请参阅以下结果:
现在输入代码:这是我用来创建纹理句柄的代码:
//texture
that.Texture = that.gl.createTexture();
that.gl.bindTexture(that.gl.TEXTURE_2D, that.Texture);
// Set the parameters so we can render any size image.
that.gl.texParameteri(that.gl.TEXTURE_2D, that.gl.TEXTURE_WRAP_S, that.gl.CLAMP_TO_EDGE);
that.gl.texParameteri(that.gl.TEXTURE_2D, that.gl.TEXTURE_WRAP_T, that.gl.CLAMP_TO_EDGE);
that.gl.texParameteri(that.gl.TEXTURE_2D, that.gl.TEXTURE_MIN_FILTER, that.gl.NEAREST);
that.gl.texParameteri(that.gl.TEXTURE_2D, that.gl.TEXTURE_MAG_FILTER, that.gl.NEAREST);
数据将加载到纹理上,如下所示:
this.gl.texImage2D(this.gl.TEXTURE_2D, 0, this.gl.RGB, this.m_iImageWidth, this.m_iImageHeight,
0, this.gl.RGB, this.gl.UNSIGNED_BYTE, this.m_aImage);
最后,这是我使用的片段着色器:
precision mediump float;
uniform sampler2D u_image;
varying vec2 v_texCoord;
void main()
{
gl_FragColor = texture2D(u_image, v_texCoord);
}
我尝试了很多选项,从过滤到设置样式选项,将图像渲染为像素化,将图像转换为RGBA并为其提供RGBA值,结果始终是糟糕的纹理渲染。即使 Canvas 与纹理的大小完全相同,WebGL似乎也无法正确插入数据。
有人提示吗?
提前致谢。
最佳答案
确保 Canvas 的宽度和高度与像素显示尺寸匹配。显示大小是通过样式的宽度和高度设置的。
分辨率是图像中的像素数。显示大小是它在页面上占用的空间量。两者应匹配以获得最佳结果。
canvas = document.createElement("canvas");
canvas.width = 1024; // set the canvas resolution
canvas.height = 784;
canvas.style.width = "1024px"; // set the display size.
canvas.style.height = "784px";
如果显示尺寸大于分辨率,则会使 Canvas 拉伸(stretch)并导致模糊