How to change face color in Three.js

前端 未结 5 1574
庸人自扰
庸人自扰 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:30

    Assuming that "myGeometry" is the geometry containing the face that you would like to change the color of, and "faceIndex" is the index of the particular face that you want to change the color of.

    // the face's indices are labeled with these characters 
    var faceIndices = ['a', 'b', 'c', 'd'];  
    
    var face = myGeometry.faces[ faceIndex ];   
    
    // determine if face is a tri or a quad
    var numberOfSides = ( face instanceof THREE.Face3 ) ? 3 : 4;
    
    // assign color to each vertex of current face
    for( var j = 0; j < numberOfSides; j++ )  
    {
        var vertexIndex = face[ faceIndices[ j ] ];
        // initialize color variable
        var color = new THREE.Color( 0xffffff );
        color.setRGB( Math.random(), 0, 0 );
        face.vertexColors[ j ] = color;
    }
    

    Then, the mesh needs to use the following material so that face colors are derived from the vertices:

    // this material causes a mesh to use colors assigned to vertices
    var cubeMaterial = new THREE.MeshBasicMaterial( 
        { color: 0xffffff, shading: THREE.FlatShading, 
        vertexColors: THREE.VertexColors } );
    

提交回复
热议问题