WebGL创建纹理

WebGL create Texture

本文关键字:纹理 创建 WebGL      更新时间:2023-09-26

我成功地从图像中创建了WebGL纹理,并将其绘制到画布元素中。

function initTexture(src) {
  texture = gl.createTexture();
  texture.image = new Image();
  texture.image.onload = function() {
    handleLoadedTexture(texture)
  }
  texture.image.src = src;
}

我还试图从其中一个数据类型创建一个纹理,但没有成功。

  • [对象图像数据]
  • [object CanvasPixelArray]
  • [object CanvasRenderingContext2D]

是否可以仅使用图像的像素阵列创建纹理?或者换句话说:是否可以从像素阵列中创建JS Image对象

编辑:

像素阵列看起来像这个[r,g,b,a,r,g,b,a,r,g,b,a,...],并且每个值都在{0..255}的范围内。我想用给定数组中的像素创建一个纹理。

用像素数组创建纹理是绝对可能的!我一直在代码中使用以下内容来创建一个单像素的纯色纹理。

function createSolidTexture(gl, r, g, b, a) {
    var data = new Uint8Array([r, g, b, a]);
    var texture = gl.createTexture();
    gl.bindTexture(gl.TEXTURE_2D, texture);
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
    return texture;
}

EDIT:要进一步推断,您需要了解的大部分内容都在gl.texImage2d调用中。为了从原始RGB(a)数据创建纹理,您需要一个无符号字节值的数组,您需要向WebGL指定数据代表的内容(RGB或RGBA),并且您需要知道纹理的尺寸。一个更广义的函数如下:

function textureFromPixelArray(gl, dataArray, type, width, height) {
    var dataTypedArray = new Uint8Array(dataArray); // Don't need to do this if the data is already in a typed array
    var texture = gl.createTexture();
    gl.bindTexture(gl.TEXTURE_2D, texture);
    gl.texImage2D(gl.TEXTURE_2D, 0, type, width, height, 0, type, gl.UNSIGNED_BYTE, dataTypedArray);
    // Other texture setup here, like filter modes and mipmap generation
    return texture;
}
// RGB Texture:
// For a 16x16 texture the array must have at least 768 values in it (16x16x3)
var rgbTex = textureFromPixelArray(gl, [r,g,b,r,g,b...], gl.RGB, 16, 16);
// RGBA Texture:
// For a 16x16 texture the array must have at least 1024 values in it (16x16x4)
var rgbaTex = textureFromPixelArray(gl, [r,g,b,a,r,g,b,a...], gl.RGBA, 16, 16);