2012-01-28 100 views
15

我成功地從圖像創建了一個WebGL紋理,並將其繪製到一個畫布元素中。WebGL創建紋理

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

    texture.image.src = src; 
} 

我也嘗試從這些數據類型之一創建紋理,但沒有成功。

  • [對象的ImageData]
  • [對象CanvasPixelArray]
  • [對象CanvasRenderingContext2D]

是否有可能創建紋理只是與圖像的像素陣列? 換句話說:是否有可能在像素數組中創建一個JS圖像對象

編輯:

像素陣列看起來像這樣[r,g,b,a,r,g,b,a,r,g,b,a,...]並且每個值在範圍{0..255}。 我想用給定數組中的像素創建紋理。

+0

對不起,也許它不是太清楚我的意思。我更新了Q. – alex 2012-01-28 16:13:23

+0

如果你的數據是在一個ArrayBuffer中,你可以使用WebGL中的一個函數(我現在不記得了) – Chiguireitor 2012-01-28 19:55:43

+0

@Chiguireitor你可以給我一個關於如何創建這樣一個arrayBuffer的例子嗎? – alex 2012-01-28 20:12:38

回答

30

用像素數組創建紋理是完全可能的!我在代碼中始終使用以下代碼創建單個像素,純色紋理。

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

編輯:推斷這個遠一點,你最需要知道的是在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); 
+0

太棒了。我有一個像素陣列[r,g,b,a,r,g,b,a,...](範圍0..255)。也許你可以給我一些例子,說明如何製作出堅實的紋理呢? – alex 2012-01-28 20:21:19

+0

對第2行的註釋是什麼意思:如果數據已經存在於類型數組中,則不需要執行此操作 – subhfyu546754 2016-02-08 14:12:59