Learning Three.js: Part 3: Loading and Using Textures


In Part 1, I covered some general terms and techniques used in Three.js, a three-dimensional rendering JavaScript library. Part 2 reviewed some of the geometry and material options in creating meshes. In this third part, I explain how to load and use textures (images) for those same meshes as a continuation of building from the first example code.

Reviewing Example Code (from Part 1)

In Part 1, the example code used a BoxGeometry as the shape for a MeshBasicMaterial with a solid color of 0xffffff (white). While materials can have solid shading of colors (and have their wireframes enabled), they can also have mapped textures loaded from other sources.


Usually, when referring to other externally loaded or internally generated images resources, the term used is texture. In three-dimensional work, these are defined in terms of three positions mapped into a space based on other objects and points. In Three.js, textures are nearly always a component of a material. Choosing which of the main material types (Basic, Lambert, or Phong) then affects how the textures appear and what effect, if any, lighting will have as well.

A 32×32 image (zoomed by 10x)

To load a texture in Three.js, the TextureLoader object is used. After defining and then setting a loaded texture object or variable, it can become the map for a material.

To expand the example from Part 1, and in using the above image, the init() section of the code would now look like this:

Note: Because of security settings, web browsers will not load resources like images across different protocols and origins. In order to correctly and safely load textures for Three.js projects, it is highly recommended to use functionality like the Live Server plugin for Atom or NetBeans’ local web-server service.

The result of the loaded texture on the rotating cube now looks like the following:


Part 3 Code (Full Example)