【问题标题】:Change the colors of a cube's faces更改立方体面的颜色
【发布时间】:2013-02-02 04:02:42
【问题描述】:

我实际上找到了this 问题,但它说material.color 不存在。我需要知道如何更改我正在绘制的立方体各个面的颜色:

var newCube = new THREE.Mesh(new three.CubeGeometry(size, size, size), new three.MeshNormalMaterial({ vertexColors: three.FaceColors }));

【问题讨论】:

    标签: javascript colors three.js mesh face


    【解决方案1】:

    此答案仅适用于 r.125 之前的 three.js 版本。

    以下是设置和更改立方体面颜色的方法:

    var geometry = new THREE.BoxGeometry( size, size, size );
    for ( var i = 0; i < geometry.faces.length; i ++ ) {
        geometry.faces[ i ].color.setHex( Math.random() * 0xffffff );
    }
    
    var material = new THREE.MeshBasicMaterial( { color: 0xffffff, vertexColors: true } );
    

    如果geometry.faces[i].color几何体被渲染后发生变化,你必须设置geometry.colorsNeedUpdate = true

    three.js r.124

    【讨论】:

    • 有更新的 ThreeJs 版本的解决方案吗?
    【解决方案2】:

    这里is a fiddle 供那些最终来到这里并希望看到此代码正常工作的人使用。

    我做了一个盒子,在脸上系了 3 种颜色:

    // colors
    red = new THREE.Color(1, 0, 0);
    green = new THREE.Color(0, 1, 0);
    blue = new THREE.Color(0, 0, 1);
    var colors = [red, green, blue];
    
    for (var i = 0; i < 3; i++) {
        geometry.faces[4 * i].color = colors[i];
        geometry.faces[4 * i + 1].color = colors[i];
        geometry.faces[4 * i + 2].color = colors[i];
        geometry.faces[4 * i + 3].color = colors[i];
    }
    

    面部颜色在animate 循环中更改。


    还要检查a related question herea great answer,以证明在THREE.BufferGeometry 实例上使用材料索引和组。

    【讨论】:

      【解决方案3】:

      对于 r.125 更高的版本

      立方体的每一面都由两个三角形组成。所以这个想法是 每次迭代处理六个顶点以创建单个 (随机)每边颜色。

      https://discourse.threejs.org/t/how-to-color-individual-faces-of-a-boxgeometry-tononindexed-object-using-vertices/30099

        const piece = new THREE.BoxGeometry(1, 1, 1).toNonIndexed();
        const material = new THREE.MeshBasicMaterial({
          vertexColors: true
        });
        const positionAttribute = piece.getAttribute('position');
        const colors = [];
      
        const color = new THREE.Color();
      
        for (let i = 0; i < positionAttribute.count; i += 6) {
      
          color.setHex(0xffffff * Math.random());
      
          colors.push(color.r, color.g, color.b);
          colors.push(color.r, color.g, color.b);
          colors.push(color.r, color.g, color.b);
      
          colors.push(color.r, color.g, color.b);
          colors.push(color.r, color.g, color.b);
          colors.push(color.r, color.g, color.b);
        } // for
      
        // define the new attribute
        piece.setAttribute('color', new THREE.Float32BufferAttribute(colors, 3));
        cube = new THREE.Mesh(piece, material);
      

      JSFiddle

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-11-22
        • 1970-01-01
        • 2012-12-20
        • 1970-01-01
        • 1970-01-01
        • 2020-08-17
        • 1970-01-01
        相关资源
        最近更新 更多