How to load an image in WebGL

Above you should see a picture of me. It looks weird, not because I look weird but because the RGB channels are swapped. This is done with a WebGL fragment shader, which looks like:

uniform sampler2D tex;
void main(void) {
  mediump vec2 coord = vec2(gl_FragCoord.x/512.0, 1.0 - (gl_FragCoord.y/512.0));
  mediump vec4 sample = texture2D(tex, coord);
  gl_FragColor = vec4(sample.b, sample.r, sample.g, 1.0);
}

To load the image into the uniform sampler2D tex, I used:

const img = new Image();
img.onload = function () {
  gl.activeTexture(gl.TEXTURE0);
  const tex = gl.createTexture();
  gl.bindTexture(gl.TEXTURE_2D, tex);
  gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE, img);
  gl.generateMipmap(gl.TEXTURE_2D);

  const texLoc = gl.getUniformLocation(prog, "tex");
  gl.uniform1i(texLoc, 0);

  gl.drawArrays(gl.TRIANGLE_FAN, 0, 4); // draw over the entire viewport
};
img.src = "/assets/jim_512.jpg";
Tagged .
đź‘‹ I'm Jim, a full-stack product engineer. Want to build an amazing product and a profitable business? Read more about me or Get in touch!

More by Jim

This page copyright James Fisher 2017. Content is not associated with my employer. Found an error? Edit this page.