I am trying to create a texture (just grey everywhere) and render it to a canvas using WebGL.
I have attempted here:
function tryToDraw() {
vertexShaderCode = `#version 100
precision mediump float;
attribute vec2 vertex_attrib;
void main (void)
{
gl_Position = vec4 (vertex_attrib, 0.0, 1.0) ;
}
`;
fragmentShaderCode = `#version 100
precision mediump float;
uniform sampler2D myTexture;
void main (void) {
vec2 texcoord = gl_FragCoord.xy / 1024.0;
gl_FragColor = vec4(texture2D (myTexture, texcoord).rgb, 1.0);
}
`;
var canvas = document.getElementById('waves_canvas');
var gl = canvas.getContext('webgl');
var program = gl.createProgram();
var textureArr = new Uint8Array(1024 * 1024 * 3).fill(128);
var vertexShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertexShader, vertexShaderCode);
gl.compileShader(vertexShader);
gl.attachShader(program, vertexShader);
var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragmentShader, fragmentShaderCode);
gl.compileShader(fragmentShader);
gl.attachShader(program, fragmentShader);
gl.linkProgram(program);
gl.validateProgram(program);
console.log(gl.getProgramParameter(program, gl.VALIDATE_STATUS));
gl.useProgram(program);
var location = gl.getUniformLocation(program, 'myTexture');
gl.uniform1i(location, 0);
var texture = gl.createTexture();
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, 1024, 1024, 0, gl.RGB, gl.UNSIGNED_BYTE, textureArr);
var vertexPositions = new Float32Array([-1.0, -1.0, 1.0, 1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0, -1.0, -1.0]);
var vertexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, vertexPositions, gl.STATIC_DRAW);
var vPosAttrLoc = gl.getAttribLocation(program, 'vertex_attrib');
gl.enableVertexAttribArray(vPosAttrLoc);
gl.vertexAttribPointer(vPosAttrLoc, 2, gl.FLOAT, false, 2 * vertexPositions.BYTES_PER_ELEMENT, null);
gl.drawArrays(gl.TRIANGLES, 0, 6);
}
tryToDraw();
<canvas id="waves_canvas"></canvas>
My understanding of loading textures in WebGL is that we load textures according to the following procedure:
- We specify which texture unit we use for our
uniform sampler2D
by usinggl.uniform1i(gl.getUniformLocation(program, 'myTexture'), 0)
. - We create a texture using
gl.createTexture()
. - We then choose which texture unit we want to load onto using
GL.activeTexture
. - We bind the texture we just created to the texture unit by using
GL.bindTexture
. - We load the texture using
GL.texImage2D
.
I've tried to implement it in the JSFiddle above, but I don't think the texture is loading correctly. I'm expecting to see a grey screen (128,128,128) which should be the texture I loaded, however all I see is a black screen.
Does anyone know if I am loading the texture correctly?