Chapter 03Coloring Faces

The easiest type of material we can apply to a mesh face is color. We can do this by using the color4() and color3() classes.

<script>
var canvas5 = document.getElementById("renderCanvas5");
var engine5 = new BABYLON.Engine(canvas5, true);

function createScene5(canvas, engine){
    let scene = new BABYLON.Scene(engine);
    scene.clearColor = new BABYLON.Color3(1, 1, 1);
    let camera = new BABYLON.ArcRotateCamera("Camera", Math.PI / 4, Math.PI / 4, 3, BABYLON.Vector3.Zero(), scene);
    camera.attachControl(canvas, true);
    let light = new BABYLON.HemisphericLight("light", new BABYLON.Vector3(1, 1, 0), scene);

    let colors = new Array(3);

    colors[0] = new BABYLON.Color4(0, 1, 0, 1);
    colors[1] = new BABYLON.Color3.Green;
    colors[2] = new BABYLON.Color3(1, 0, 0);

    let cylinder = BABYLON.MeshBuilder.CreateCylinder("cylinder", {faceColors: colors}, scene);
    return scene;
};

var scene5 = createScene5(canvas5, engine5);

engine5.runRenderLoop(function(){
    scene5.render();
});

window.addEventListener("resize", function(){
    engine5.resize();
});
</script>

<canvas id="renderCanvas5"></canvas>

Color4

colors[0] = new BABYLON.Color4(0, 1, 0, 1);

The color4() class takes four number values between 0 and 1 as arguments. In order, the arguments are red, green, blue, and alpha. The red, blue, and green arguments specify the amount of each color that is used to color the selected space. The alpha argument specifies the transparency of the color in the selected space, where the value 0 is fully transparent and the value 1 is fully opaque.

In the example above, we made the face of the cylinder corresponding to index 0 in the colors array an opaque green.

Color3 and Built-in Colors

colors[2] = new BABYLON.Color3(0, 0, 1);

The color3() class takes three number values between 0 and 1 as arguments. In order, the arguments are red, green, and blue. The red, green, and blue arguments specify the amount of each color that is used to color the selected space.

In the example above, we made the face of the cylinder corresponding to index 2 in the colors array blue.

colors[1] = new BABYLON.Color3.Red;

The color3() class also has built-in colors we can use, rather than specifying values.

The built-in colors are:

In the example above, we made the face of the cylinder corresponding to index 1 in the colors array red.