To ensure optimal performance, it is recommended to retain your texture's images. During initialization, for each image that will be converted into a texture, create a duplicate of its data using the following method:
// set up a canvas with the same dimensions as the image
some2dCanvasCtx.canvas.width = img.width;
some2dCanvasCtx.canvas.height = img.height;
// draw the image onto the canvas
some2dCanvasCtx.drawImage(img, 0, 0);
// copy the canvas contents
var texData = some2dCanvasCtx.getImageData(0, 0, img.width, img.height);
With the UV coordinates at hand, you can easily retrieve the corresponding color by:
var tx = Math.min(emod(u, 1) * texData.width | 0, texData.width - 1);
var ty = Math.min(emod(v, 1) * texData.height | 0, texData.height - 1);
var offset = (ty * texData.width + tx) * 4;
var r = texData.data[offset + 0];
var g = texData.data[offset + 1];
var b = texData.data[offset + 2];
var a = texData.data[offset + 3];
// only necessary if UV coords are outside the range [0, 1]
// for CLAMP_TO_EDGE, ensure to clamp UVs within this range instead.
function emod(n, m) {
return ((n % m) + m) % m;
}
If needed, WebGL can provide the texture color using the values of tx
and ty
. Refer to this answer for more details.