更改使用face3创建的网格的颜色

时间:2018-07-04 11:00:47

标签: javascript html three.js

我使用第3面和第3个js创建了一个网格。但是所需的颜色不会在网格上反射。这是我使用的代码。

var geometry = new THREE.Geometry();
var f = 0;
for (var i = 0; i < data.real.length; i++, f += 4) {
    var o2 = i == data.real.length - 1 ? 0 : i + 1;
    var tl = data.real[i];
    var tr = data.real[o2];
    var bl = data.zeroAxis[i];
    var br = data.zeroAxis[o2];

    geometry.vertices.push(tl, tr, br, bl);
    geometry.faces.push(new THREE.Face3(f, f + 1, f + 2));
    face.materials = [ new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } ) ];

    geometry.faces.push(new THREE.Face3(f, f + 3, f + 2));
}
var material = new THREE.MeshPhongMaterial({
    color : new THREE.Color(0x008000),
    side : THREE.DoubleSide,
    transparent : true,
    opacity : 0.5
});
var object = new THREE.Mesh(geometry, material);
object.position.set(0, 0, 0);
this.plot = object;
this.tb.scene.add(object);
this.tb.render();

3 个答案:

答案 0 :(得分:0)

以下行不正确:

face.materials = [ new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } ) ];

如果要在每个面上应用颜色,请按照以下步骤进行操作:

var faces = geometry.faces;

for ( var i = 0, l = faces.length; i < l; i ++ ) {

    var face = faces[ i ];
    face.color = new THREE.Color( Math.random() * 0xffffff );

}

还将相应材质的属性vertexColors设置为THREE.FaceColors。请查看以下实时演示,以查看完整的示例:https://jsfiddle.net/f2Lommf5/8539/

答案 1 :(得分:0)

如果不提供脸部法线,则需要计算法线。看一下Face3 docs的最佳示例:

//the face normals and vertex normals can be calculated automatically if not supplied above
geometry.computeFaceNormals();
geometry.computeVertexNormals();

答案 2 :(得分:0)

感谢您的答复,我使用以下代码解决了上述问题。

var normal = new THREE.Vector3(0, 1, 0); // optional
    var color = new THREE.Color(color); // optional
    var materialIndex = 0; // optional
    geometry.faces.push(new THREE.Face3(f, f + 1, f + 2, normal, color,
            materialIndex));
    geometry.faces.push(new THREE.Face3(f, f + 2, f + 3, normal, color,
            materialIndex));

请提出改进​​建议。