[英]WebGL create Texture
我成功地從圖像創建了一個WebGL紋理並將其繪制到一個canvas元素中。
function initTexture(src) {
texture = gl.createTexture();
texture.image = new Image();
texture.image.onload = function() {
handleLoadedTexture(texture)
}
texture.image.src = src;
}
我還試圖從這些數據類型之一創建紋理,但沒有成功。
是否可以使用圖像的像素陣列創建紋理? 或者換句話說:是否可以從像素數組中創建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;
}
編輯:要進一步推斷這一點,你需要知道的大部分內容都是在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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.