Lesson 2: Colors

View the full source.

In the previous lesson, you drew white triangles and squares on the screen. In this lesson, you will learn how to give control how actors are painted on the screen by changing their colors.

If all vertices in the model share the same color, then the color can be specified directly in the appearance, at the site of the actor creation. We use the Shade.color function to specify a function. The following snippet produces the bluish triangle on the right:

var square = Lux.model({
    type: "triangles",
    elements: [0, 1, 2, 0, 2, 3],
    vertex: [[-1,-1, 1,-1, 1,1, -1,1], 2]});
Lux.Scene.add(Lux.actor({
    model: square, 
    appearance: { 
        position: camera(Shade.translation( 1.5, 0, -6)(square.vertex)),
        color: Shade.color('#88f')}}));

If you wanted to specify the color directly as a vector of its RGBA components, you would use the Shade.vec call. Notice that each color has four components, the last of which is the opacity component, or alpha (More about alpha on lesson 8):

var appearance = { position: some_position,
                   color: Shade.vec(1, 0.4, 0.2, 1) };

As you learned in the previous lesson, the field elements tells Lux how to build the triangles in the model, three at a time. So the first triangle is comprised of the vertices at indices 0, 1, and 2, while the second triangle has indices 0, 2, and 3.

In addition, models are specified vertex by vertex. In the same way that model vertices have positions (given by the vertex field), they can have colors as well. These colors can then be specified on the model itself:

var triangle = Lux.model({
    type: "triangles",
    elements: [0, 1, 2],
    vertex: [[0,1, -1,-1, 1,-1], 2],
    color: [Shade.color('red'),
            Shade.color('green'),
            Shade.color('blue')]});

For convenience, Shade.color accepts all CSS color names, and hex values as well. In addition, color attributes can also be specified as an array of values, exactly like positions. This snippet is exactly equivalent to the one above:

var triangle = Lux.model({
    type: "triangles",
    elements: [0, 1, 2],
    vertex: [[0,1, -1,-1, 1,-1], 2],
    color: [[1,0,0,1, 0,0.5,0,1, 0,0,1,1], 4]});

To draw the square with different colors, you need to tell Lux.actor to use those colors:

Lux.Scene.add(Lux.actor({
    model: triangle, 
    appearance: { position: camera(Shade.translation(-1.5, 0, -6)(triangle.vertex)),
                  color: triangle.color }}));

Back to the index.