gpt4 book ai didi

javascript - 将背景图像添加到 WebGL 3D 场景

转载 作者:行者123 更新时间:2023-11-30 12:55:41 26 4
gpt4 key购买 nike

我编写了一段代码,试图在 WebGL 3D 场景中仅绘制背景图像。以下是代码的相关部分:

<script id="shader-fs" type="x-shader/x-fragment">
varying highp vec2 vTexCoord;

uniform sampler2D uSampler;

void main(void) {
gl_FragColor = texture2D(uSampler, vec2(vTexCoord.s, vTexCoord.t));
}
</script>

<script id="shader-vs" type="x-shader/x-vertex">
attribute vec3 aVertexPosition;
attribute vec2 aTextureCoord;

uniform mat4 uMVMatrix;
uniform mat4 uPMatrix;

varying highp vec2 vTexCoord;

void main(void) {
gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
vTexCoord = aTextureCoord;
}
</script>

<script>
var VBack = [
-24.0, 0.0, 0.0,
24.0, 0.0, 0.0,
24.0, 48.0, 0.0,
-24.0, 48.0, 0.0
];

var vTBack = [
0.0, 0.0,
1.0, 0.0,
1.0, 1.0,
0.0, 1.0
];

var VBuffer;
var vTBuffer;

function initMatrix() {
orthoMatrix = makeOrtho(-24.0, 24.0, 0.0, 48.0, 20.0, -20.0); // From glUtils.js
mvMatrix = Matrix.I(4);
...
}

function handleBkTex(tex) {
GL.bindTexture(GL.TEXTURE_2D, tex);
GL.pixelStorei(GL.UNPACK_FLIP_Y_WEBGL, true);
GL.texImage2D(GL.TEXTURE_2D, 0, GL.RGBA, GL.RGBA, GL.UNSIGNED_BYTE, tex.Img);
GL.texParameteri(GL.TEXTURE_2D, GL.TEXTURE_MAG_FILTER, GL.NEAREST);
GL.texParameteri(GL.TEXTURE_2D, GL.TEXTURE_MIN_FILTER, GL.NEAREST);
GL.bindTexture(GL.TEXTURE_2D, null);
}

function initBkgnd() {
backTex = GL.createTexture();
backTex.Img = new Image();
backTex.Img.onload = function() {
handleBkTex(backTex);
}
backTex.Img.src = "Bkgnd.jpg";
}

function drawBkgnd() {
GL.bindBuffer(GL.ARRAY_BUFFER, VBuffer);
GL.vertexAttribPointer(vertexPositionAttribute, 3, GL.FLOAT, false, 0, 0);

GL.bindBuffer(GL.ARRAY_BUFFER, vTBuffer);
GL.vertexAttribPointer(texCoordAttribute, 2, GL.FLOAT, false, 0, 0);

GL.activeTexture(GL.TEXTURE0);
GL.bindTexture(GL.TEXTURE_2D, backTex);
GL.uniform1i(GL.getUniformLocation(shaderProgram, "uSampler"), 0);

GL.drawArrays(GL.TRIANGLE_STRIP, 0, 4);
}


function start() {
var canvas = document.getElementById("glcanvas");
initWebGL(canvas);

if (GL) {
initShaders();
initBuffers();
initMatrix();
initBkgnd();
drawBkgnd();
}
}

Canvas 大小为 512 x 512,与图像大小相同。但是我没有在 Canvas 上得到正确的图像。如何正确执行此操作?

最佳答案

您想要的答案是如何设置 3D 矩阵来绘制 2D 图像,还是想要答案是如何有效地做到这一点?

这是有效的答案。没有理由用 3D 来画 2D。将顶点更改为

var VBack = [
-1, -1,
1, -1,
1, 1,
-1, 1,
];

将对 vertexAttribPointer 的调用更改为

GL.vertexAttribPointer(vertexPositionAttribute, 2, GL.FLOAT, false, 0, 0);

将顶点着色器更改为

attribute vec4 aVertexPosition;
attribute vec2 aTextureCoord;

varying highp vec2 vTexCoord;

void main(void) {
gl_Position = aVertexPosition;
vTexCoord = aTextureCoord;
}

它应该可以工作。

参见 this set of articles for more about 2D in WebGL了解更多。

关于javascript - 将背景图像添加到 WebGL 3D 场景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19239369/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com