我正在尝试将RGBA格式的像素渲染到WebGL画布。我有这个画布:
<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画布:
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/
提供了一个小提琴答案 0 :(得分:2)
您刚刚将图片上传到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);