gpt4 book ai didi

JavaScript WebGL RGBA 数组到屏幕?

转载 作者:行者123 更新时间:2023-11-30 17:56:05 27 4
gpt4 key购买 nike

我正在尝试将 RGBA 格式的像素渲染到 WebGL Canvas 。我有这个 Canvas :

<canvas id="cv" width="100" height="100"></canvas>

使用以下初始化代码渲染一个红色矩形:

var w = 100;
var h = 100;
var img = new Uint8Array(w * h * 4);
for (var i = 0; i < img.length; i += 4) {
img[i + 0] = 255; // r
img[i + 1] = 0; // g
img[i + 2] = 0; // b
img[i + 3] = 255; // a
}

现在我尝试使用以下代码将此数组渲染到 WebGL Canvas :

var cv = document.getElementById('cv');
var gl = cv.getContext('webgl');
var tex = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.texImage2D(
gl.TEXTURE_2D, // target
0, // mip level
gl.RGBA, // internal format
w, h, // width and height
0, // border
gl.RGBA, //format
gl.UNSIGNED_BYTE, // type
img // texture data
);

什么都不会出现。我做错了什么? http://jsfiddle.net/AMHRZ/ 上有 fiddle 可用

最佳答案

您只是将图像上传到 WebGL 上下文,仅此而已。如果你想显示这个纹理,那么创建着色器对象,为你的纹理分配一个有效的过滤器,创建带有屏幕坐标的顶点缓冲区。

这里是修改后的代码:http://jsfiddle.net/XfyX2/

var w = 128;
var h = 128;
var img = new Uint8Array(w * h * 4);
for (var i = 0; i < img.length; i += 4) {
img[i + 0] = 255; // r
img[i + 1] = 0; // g
img[i + 2] = 0; // b
img[i + 3] = 255; // a
}

var cv = document.getElementById('cv');
var gl = cv.getContext('experimental-webgl');
var tex = gl.createTexture();
var vbo = gl.createBuffer();
var program = gl.createProgram();
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texImage2D(
gl.TEXTURE_2D, // target
0, // mip level
gl.RGBA, // internal format
w, h, // width and height
0, // border
gl.RGBA, //format
gl.UNSIGNED_BYTE, // type
img // texture data
);
gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
gl.bufferData(gl.ARRAY_BUFFER,
Float32Array([-1, -1,
1, -1,
1, 1,
1, 1,
-1, 1,
-1, -1]), gl.STATIC_DRAW);

program.vs = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(program.vs,
"attribute vec4 vertex;\n" +
"varying vec2 tc;\n" +
"void main(){\n" +
" gl_Position = vertex;\n" +
" tc = vertex.xy*0.5+0.5;\n" +
"}\n");

program.fs = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(program.fs,
"precision highp float;\n" +
"uniform sampler2D tex;\n" +
"varying vec2 tc;\n" +
"void main(){\n" +
" gl_FragColor = texture2D(tex, tc);\n" +
"}\n");

gl.compileShader(program.vs);
gl.compileShader(program.fs);

gl.attachShader(program,program.vs);
gl.attachShader(program,program.fs);

gl.deleteShader(program.vs);
gl.deleteShader(program.fs);
gl.bindAttribLocation(program, 0, "vertex");
gl.linkProgram(program);
gl.useProgram(program);
gl.enableVertexAttribArray(0);
gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.drawArrays(gl.TRIANGLES, 0, 6);

关于JavaScript WebGL RGBA 数组到屏幕?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18043144/

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