## Lesson 3 - Color Your Polygons!

#### Introduction

Now that we have covered creating polygons, let's give them some color. Most of the source code is identical boilerplate to the second lesson so this lesson is much shorter.

Again, we instantiate a scene and call initializeScene()where all the work gets done. Similarly, the creation of the triangle and the square is identical to the second lesson, with one exception - how we specify the color.

In the second lesson, we created the mesh like this

``````var triangleMaterial = new THREE.MeshBasicMaterial({
color:0xFFFFFF,
side:THREE.DoubleSide
});``````

This time, we want each vertex of the triangle to be a different color. Then those colors will be interpolated across the surface of the triangle. First, we create the colors themselves by specifying the color of the three vertexes in the one face that we created.

``````triangleGeometry.faces.vertexColors = new THREE.Color(0xFF0000);
triangleGeometry.faces.vertexColors = new THREE.Color(0x00FF00);
triangleGeometry.faces.vertexColors = new THREE.Color(0x0000FF);``````

In order for those colors to be used we have to tell three.js when we create the mesh to use those vertex-colors:

``````var triangleMaterial = new THREE.MeshBasicMaterial({
vertexColors:THREE.VertexColors,
side:THREE.DoubleSide
});``````

BTW, notice the curly braces inside the call to the constructor THREE.MeshBasicMaterial. Three.js uses JSON syntax for most its function parameter lists. This is very handy and flexible. We'll use the same approach later when we start refactoring the lessons.

And that's how it is done. Note that under the covers, three.js creates a shader which handles the color interpolation. A shader is a function written in OpenGL Shader language (which we'll touch on later on). The shader is passed to the graphics hardware and it drives those thousands of GPU cores to iterate across the surface of the triangle to render the color gradients.

The square is similar to lesson 2 except that we specify a pale blue color.

``````var squareMaterial = new THREE.MeshBasicMaterial({
color:0x8080FF,
side:THREE.DoubleSide
});``````

And that's it! Click on this link to see the actual rendered demo in all it's rainbow glory!

As always, the original sources are on github here.