Gabriel A. Zorrilla - 8 months ago 43

Javascript Question

Is there a way to programatically change the color of a face than pre-creating a pallet of materials and then assign based on the vertex value? I have this:

`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);

});

Would like something like:

`[..]`

$.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);

}

}

[..]

Thanks!

Answer Source

As an example

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

if you want to set color with `r`

, `g`

, `b`

components, then values of components must be from 0 to 1, not from 0 to 255. Each face is of `Face3`

type, which has properties `a`

, `b`

, `c`

, where indices of vertices stored.