How to change face color in Three.js

前端 未结 5 1576
庸人自扰
庸人自扰 2020-11-30 10:56

I am attempting to change the color on a single face of a mesh. This is in a WebGL context. I can change the entire mesh color, just not a single Face. Relevant code belo

5条回答
  •  甜味超标
    2020-11-30 11:34

    I think the method listed above only works in the WebGLRenderer. If you're going for something that works in both the CanvasRenderer and WebGLRenderer it's a bit more complicated, but I suspect the end result is more efficient both in terms of memory use and performance.

    After going through the THREE.jS Projector.js source, this is how I did it:

    // create the face materials
    var material_1 = new THREE.MeshLambertMaterial(
        {color : 0xff0000, shading: THREE.FlatShading, overdraw : true}
    );
    var material_2 = new THREE.MeshLambertMaterial(
        {color : 0x00ff00, shading: THREE.FlatShading, overdraw : true}
    );
    
    // create a geometry (any should do)
    var geom = new THREE.CubeGeometry(1,1,1);
    
    // add the materials directly to the geometry
    geom.materials.push(material_1);
    geom.materials.push(material_2);
    
    // assign the material to individual faces (note you assign the index in 
    // the geometry, not the material)
    for( var i in geom.faces ) {
        var face = geom.faces[i];
        face.materialIndex = i%geom.materials.length;
    }
    
    // create a special material for your mesh that tells the renderer to use the 
    // face materials
    var material = new THREE.MeshFaceMaterial();
    var mesh = new THREE.Mesh(geom, material);
    

    This example is adapted from the working code I have, but I have to admit I haven't actually run this exact block of code and I don't have a great track record of getting everything right first go, but hopefully it will help anyone who's struggling

提交回复
热议问题