user1763510
user1763510

Reputation: 1260

WebGL Texture pixel unexpected color in PNG

I am trying to load a texture into WebGl and read a pixel color from it (to eventually use in a shader). When I read the pixel color at position 70,70 in python, I get (255,0,0,255) which is what I expected. But when I read it in WebGL, I get (255,38,0,255). What am I missing here?

Image: https://i.sstatic.net/90BwS.png

JSFiddle: https://jsfiddle.net/6u7h0sj1/3/

Python code:

import requests
from io import BytesIO

response = requests.get('https://i.sstatic.net/90BwS.png')
im = Image.open(BytesIO(response.content))
pixels=im.load()
print(pixels[70,70])

Javascript code to read pixel of texture:

const canvas = document.createElement('canvas');
document.body.appendChild(canvas);

const gl= canvas.getContext("webgl",{"antialias":true});

function loadTexture(){
  const texture = gl.createTexture();
  gl.bindTexture(gl.TEXTURE_2D, texture);

  const level = 0;
  const internalFormat = gl.RGBA;
  const width = 1;
  const height = 1;
  const border = 0;
  const srcFormat = gl.RGBA;
  const srcType = gl.UNSIGNED_BYTE;
  const pixel = new Uint8Array([0, 0, 255, 255]);  // opaque blue
  gl.texImage2D(gl.TEXTURE_2D, level, internalFormat,
                width, height, border, srcFormat, srcType,
                pixel);

  const image = new Image();
    image.crossOrigin = "";  // or "anonymous", will be interpreted the same
  image.onload = () => {
    gl.bindTexture(gl.TEXTURE_2D, texture);
    gl.texImage2D(gl.TEXTURE_2D, level, internalFormat,
                  srcFormat, srcType, image);

    let width=1;
    let height=1;
    let x=70;
    let y=70;
    var fb = gl.createFramebuffer();
    gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
    gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
    if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) == gl.FRAMEBUFFER_COMPLETE) {
      var pixels = new Uint8Array(width * height * 4);
      gl.readPixels(x, y, width, height, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
      document.getElementById("test").textContent=pixels;

    }
  };
  image.src = 'https://i.sstatic.net/90BwS.png';
}

loadTexture();

Upvotes: 0

Views: 206

Answers (1)

user1763510
user1763510

Reputation: 1260

Found this helpful answer:

Fragment Shader: wrong color value from texture

Solved by adding the following line before loading the texture:

gl.pixelStorei(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, false);

Upvotes: 0

Related Questions