在UV坐标处获取纹理的颜色

时间:2016-01-26 01:29:44

标签: javascript three.js textures webgl

我正在使用三个v.73 我从raycaster的交叉点有UV坐标。 我也有这个对象的纹理。如何在UV坐标处获得所用纹理的颜色(RGB或RGBA)?

我曾尝试从纹理中使用Image的像素,但它使用了大量的内存

1 个答案:

答案 0 :(得分:3)

如果你想快速保持你的纹理图像。在每个图像的初始化时,您正在制作纹理,并使用类似

的内容复制其数据
// make the canvas same size as the image
some2dCanvasCtx.canvas.width  = img.width;
some2dCanvasCtx.canvas.height = img.height;
// draw the image into the canvas
some2dCanvasCtx.drawImage(img, 0, 0);
// copy the contents of the canvas
var texData = some2dCanvasCtx.getImageData(0, 0, img.width, img.height);

现在如果你有一个UV坐标,你可以查一查

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

// this is only needed if your UV coords are < 0 or > 1
// if you're using CLAMP_TO_EDGE then you'd instead want to
// clamp the UVs to 0 to 1.
function emod(n, m) {
  return ((n % m) + m) % m;
}

否则,您可以向WebGL询问纹理的颜色。从上方使用txtySee this answer