Unable to render image using WebGL

一曲冷凌霜 提交于 2019-12-12 03:32:54

问题


I am referring to this Link and trying the same in my local.

However, the code works without any problem, if I change the source of image of any width*height, but it fails to load (shows a black image) if I prepare a Uint8Array and then render it.

Here's my Code:

function renderImage (u8a) {
 if(dataTypedArray != null) {
     gl.clear(gl.COLOR_BUFFER_BIT || gl.DEPTH_BUFFER_BIT);
     u8a = dataTypedArray;
     image.width = tempImg.width;
     image.height = tempImg.height;
     gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, image.width, image.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, u8a);
        //Draw the rectangle.
        gl.drawArrays(gl.TRIANGLES, 0, 6);
      renderTexture();
 }

}

Where dataTypedArray is the Uint8Array created by myself.

Mainly when I am adding image data to a canvas, it works fine, but when I add canvas to texture, it fails.

 var renderData = function (imageAttr) {
 var data = imageAttr.data;
  var LINES_PER_CHUNK = imageAttr.lines;
 var alpha = 4;
 if(imageAttr.newBag) {
    newBuffer = new ArrayBuffer(imageAttr.width * imageAttr.height * alpha);
    dataTypedArray = new Uint8Array(newBuffer);
} else {
    for (var z = imageAttr.index; z > 0; z--) {
        for (i = 0 ; i < LINES_PER_CHUNK; i++) {
            for (j = 0 ; j < imageAttr.height; j++) {
                dataTypedArray[i * alpha + imageAttr.width*alpha * j + 3 + LINES_PER_CHUNK  * alpha * z] = dataTypedArray[i * alpha + imageAttr.width*alpha * j +  3 + LINES_PER_CHUNK  * alpha * (z-1)];
            }
        }
    }
}
for (i = 0, k = imageAttr.height*LINES_PER_CHUNK; i < LINES_PER_CHUNK; i++) {
    for (j = 0 ; j < imageAttr.height; j++) {
        dataTypedArray[i * alpha + imageAttr.width*4 * j + 3] = data[k - imageAttr.height + j];
    }
    k = k - imageAttr.height;
}
imageAttrTemp = imageAttr;
var can1 = document.getElementById('canvas1');
  can1.width = imageAttr.width; can1.height = imageAttr.height;
  var ctx = can1.getContext('2d');
  var imageData = ctx.getImageData(0, 0, imageAttr.width, imageAttr.height);
  for (i = 3 ; i < dataTypedArray.byteLength; i=i+4) {
      imageData.data[i] = dataTypedArray[i];
  }
  ctx.putImageData(imageData, 0,0);
  image.width=can1.width;
  image.height = can1.height;
  setupGLSL();
  renderImageLineByLine(can1);
};
var proto = 'ws://';
if(location.protocol === 'https:'){
    proto = 'wss://';
}
var ws = new WebSocket(proto + location.host + '/dashboard');
ws.binaryType = 'arraybuffer';
ws.onmessage = function(event) {
    try {
        var imageAttr = JSON.parse(event.data);
       renderData(imageAttr);
    } catch(E) {
       console.log(E);
    }
};
ws.onopen = function(event) {
   console.log('Con opened');
};
ws.onerror = function(event){
    console.log('Con error');
};

来源:https://stackoverflow.com/questions/35766596/unable-to-render-image-using-webgl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!