Threejs:我可以根据顶点值在PlaneGeometry中更改面部颜色吗?

时间:2016-11-23 04:10:42

标签: javascript three.js

有没有办法以编程方式改变面部颜色而不是预先创建材料托盘,然后根据顶点值进行分配?我有这个:

var materials = [];
materials.push([..] //add all the materials here.

var geometry = new THREE.PlaneGeometry(gs, gs, size, size);
$.getJSON('http://localhost:5000', function (data) {
    for (var i = 0, l = geometry.vertices.length; i < l; i++) {
        geometry.vertices[i].z = data.map[i] / 255;
        if (geometry.vertices[i].z > 1) {
            geometry.faces[i].materialIndex = 1;
        } else {
            geometry.faces[i].materialIndex = 0;
        }
    }
    var plane = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials));
    scene.add(plane);
});

想要像:

[..]
    $.getJSON('http://localhost:5000', function (data) {
        for (var i = 0, l = geometry.vertices.length; i < l; i++) {
            geometry.vertices[i].z = data.map[i] / 255;
            if (geometry.vertices[i].z > 1) {
                geometry.faces[i].setrgb(i*128, i*2, i*96);
            } else {
                geometry.faces[i].setrgb(i*12, i*2, i*96);
            }
        }
[..]

谢谢!

1 个答案:

答案 0 :(得分:2)

作为一个例子

var size = 10; // just for example
...
planeGeom = new THREE.PlaneGeometry(size, size, 10, 10);
...
planeGeom.faces.forEach(function(face){
  var val = planeGeom.vertices[face.a].y;
  face.color.setRGB(Math.abs(val) / size * 2, 0, 0);
});
planeGeom.colorsNeedUpdate = true;

如果要使用rgb组件设置颜色,则组件的值必须为0到1,而不是0到255.每个面都是Face3类型,其属性为abc,其中存储了顶点索引。

jsfiddle