如果您必须使用`new Image`在WebGL中渲染图像

时间:2019-03-13 21:27:03

标签: image browser webgl pixel

我为WebGL绘图图像看到的示例都使用DOM Image对象:

var image = new Image();
image.src = "resources/f-texture.png";
image.addEventListener('load', function() {
  // Now that the image has loaded make copy it to the texture.
  gl.bindTexture(gl.TEXTURE_2D, texture);
  gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA,gl.UNSIGNED_BYTE, image);
  gl.generateMipmap(gl.TEXTURE_2D);
});

想知道是否有办法将像素保存在ArrayBuffer或其他东西中,而不是使用Image对象,然后将其绘制为图像。如果是这样,通常想知道代码看起来是否可以完成该任务。那太好了,因为这样我就可以将像素数据也用于其他用途,因此不必重复下载图像像素数据。

1 个答案:

答案 0 :(得分:1)

您可能应该read some tutorials on WebGL

是的,您可以将数据从ArrayBuffer加载到纹理

gl.bindTexure(gl.TEXTURE_2D, tex);
const data = new Uint32Array([
   255, 0, 0, 255, // red
   0, 255, 0, 255, // green
   0, 0, 255, 255, // blue
   255, 255, 0, 255, // yellow
]);
const level = 0;
const internalFormat = gl.RGBA;
const width = 2;
const height = 2;
const border = 0;
const format = gl.RGBA;
const type = gl.UNSIGNED_BYTE
gl.texImage2D(gl.TEXTURE_2D, level, internalFormat, width, height, border,
              format, type, data);
gl.generateMipmap(gl.TEXTURE_2D);