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() {
  const tex = gl.createTexture();
  gl.bindTexture(gl.TEXTURE_2D, tex);
  gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE, img);

  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';

Get updates on Twitter

I wrote this because I felt like it. This post is not associated with my employer. This site is hosted by Netlify (who are great, but I'm not associated with them either).