Lesson 6 - Texture This!



Now that we have added some depth, it's time to move on from simple colors to something a little more exciting. We're going to create a single cube again, but this time, instead of color, we'll apply a texture to it - where the texture is drawn from an image. Three.js does most of the heavy lifting here, so this is a fairly short lesson.

Again, we instantiate a scene and call initializeScene()where all the work gets done.


First we need to create the cube. This is easy to as three.js provides a BoxGeometry. which takes just the same three parameters:

var cubeGeometry = new THREE.BoxGeometry(1.5, 1.5, 1.5);

Note that like most three.js objects, BoxGeometry takes more than 3 parameters, but it's all we need here.

Next we need to load the texture, which is pretty easy

var neheTexture = new THREE.ImageUtils.loadTexture("../images/NeHe.jpg");

Again, there are a LOT more parameters to loading a texture (and displaying it), but we'll come back to those in a later lesson. For now we need to use the texture to create a new material for our cube.

var cubeMaterial = new THREE.MeshBasicMaterial({

The we just create the mesh, same as before and insert the geometry and the material. Translate the whole mesh by by 4 on the z axis and add the mesh to the scene.

cubeMesh = new THREE.Mesh(cubeGeometry, cubeMaterial);
cubeMesh.position.set(1.5, 0.0, 4.0);


Again, we animate them in our animateScene function. This time we want the rotations to be different on each axis (just for fun), so we define 3 variables

var xRotation = 0.0;
var yRotation = 0.0;
var zRotation = 0.0;

And then we increment each of them separately in our animateScene function.

xRotation += 0.03;
yRotation += 0.02;
zRotation += 0.04;
cubeMesh.rotation.set(xRotation, yRotation, zRotation);

And that's it! Go on to the this link to see the actual rendered demo in all its textured glory!

As always, the original sources are on github here.

About Us | Contact Us | ©2017 Geo-F/X