Please enable JavaScript to use CodeHS

Games & Animations with Three.js

Textures in Three.js

Up to now every object has been one flat color. In this part you wrap a picture around a shape instead: you draw the picture yourself on a 2D canvas, paint on it with your finger or mouse, and watch it update on a spinning cube the same instant.

Part 8 of 12 ~15 min JavaScript
Part 8 of 12

What you'll learn

  • What a texture is (an image wrapped around a shape) and how a material's map property replaces its single color with a whole picture.
  • How to make a texture with no image file at all: draw on a 2D <canvas>, hand it to THREE.CanvasTexture, and set needsUpdate whenever you draw again.
  • What a UV coordinate is, in one sentence, and why the same picture looks different on a cube, a sphere, and a plane.
  • How RepeatWrapping and repeat turn a tiny tile into an endless floor, and how offset makes it scroll like a conveyor belt.

The Big Idea

A texture is a picture wrapped around a shape

Look at any 3D game. The walls have bricks. The ground has grass. Characters have faces, and the crates have logos and scratches. Almost none of that is modeled out of tiny shapes. It is painted on. A texture is an ordinary 2D image that gets stretched over the surface of a 3D shape, like gift wrap around a box or a sticker smoothed onto a ball. The shape stays simple; the picture does the work of making it look real.

In Part 4 you gave a material a color, and every point on the surface got that same color. A texture goes on a material too, but through a different property: map. Write new THREE.MeshStandardMaterial({ map: texture }) and now every point on the surface looks up its own color from the picture. Lights, shadows, roughness, and metalness all still work exactly as before, because the texture only replaces the "what color is this spot" part of the material.

Where does the picture come from? Most games load image files: new THREE.TextureLoader().load('bricks.png') fetches a file from the same web server as your page and turns it into a texture in one line. This page does something different, and it turns out to be the best way to understand what a texture really is. A web page already has a way to draw pictures with code: the 2D <canvas>, with fillRect, arc, and gradients. three.js can take that canvas and use it as a texture directly: new THREE.CanvasTexture(canvas). Change the drawing, tell the texture it changed, and the 3D object changes. No image file, no server, no waiting. Real games do this constantly: scoreboards, name tags, minimaps, and any pattern a loop can draw.

That is the "aha" of this page, and the demo below makes it literal. You paint on a flat square, and your strokes show up on a spinning cube at the same moment, because the cube's skin is that square.

Simple definition: a texture is a 2D image that a material spreads across the surface of a 3D shape. You attach it with the material's map property. The image can come from a file (TextureLoader) or from a picture you draw with code (CanvasTexture). Either way, the shape decides where each part of the image lands, using coordinates called UVs.


How It Works

Canvas, map, UVs, repeat

We keep the setup from Part 1 (scene, camera, renderer, lights) and the delta-time loop from Part 7. Everything new on this page is about making the picture and attaching it.

1. Draw a picture, then make it a texture

A <canvas> element is a blank rectangle of pixels. You never even have to put it on the page; document.createElement('canvas') makes one that lives only in memory. Set its width and height in pixels, ask for its 2D drawing context with getContext('2d'), and you have a pen. Two nested loops and fillRect draw a checkerboard: the outer loop walks down the rows, the inner loop walks across the columns, and (row + col) % 2 flips between two colors so neighbors never match.

Then two lines you will write for every texture. new THREE.CanvasTexture(canvas) wraps the canvas as a texture. And texture.colorSpace = THREE.SRGBColorSpace tells three.js the picture holds real, on-screen colors. Since r152, three.js does its lighting math in a "linear" color space and assumes a texture is linear data unless you say otherwise; a picture of colors is not, so without this line the checkerboard comes out pale and washed out. Set it on every texture that is a picture, whether it came from a file or a canvas.

checkerboard.js
// 1. A blank 256×256 picture that lives only in memory, and a pen to draw with
const canvas = document.createElement('canvas');
canvas.width = 256;
canvas.height = 256;
const ctx = canvas.getContext('2d');

// 2. An 8×8 checkerboard: two nested loops, one square per turn
const SQUARES = 8;
const size = canvas.width / SQUARES;   // 32 pixels per square
for (let row = 0; row < SQUARES; row++) {
  for (let col = 0; col < SQUARES; col++) {
    ctx.fillStyle = (row + col) % 2 === 0 ? '#fb923c' : '#0b1220';   // tangerine, navy
    ctx.fillRect(col * size, row * size, size, size);
  }
}

// 3. Turn the picture into a texture, and say it holds real colors (not washed out)
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;

// 4. map instead of color: every spot on the surface reads its color from the picture
const material = new THREE.MeshStandardMaterial({ map: texture });
const cube = new THREE.Mesh(new THREE.BoxGeometry(1.6, 1.6, 1.6), material);
scene.add(cube);

This is the cube in the hero stage, and the Checkerboard preset in "Try it." Change SQUARES to 2 and you get a four-square flag; change it to 32 and you get a fine grid.

If you do have an image file, the canvas steps disappear and the loader does the work. Two rules: the file must be hosted next to your page, and it arrives asynchronously. The line returns at once, and the picture shows up a moment later when the download finishes.

load-image.js · only if you have an image file
// The one-liner most games use. bricks.png must sit next to your .html on the server.
const texture = new THREE.TextureLoader().load('bricks.png');
texture.colorSpace = THREE.SRGBColorSpace;   // same rule: it is a picture of colors
const material = new THREE.MeshStandardMaterial({ map: texture });

Not used on this page (no image files here), but it is the same texture object with the same map, repeat, and offset properties, so everything below applies to it too.

2. UVs: how the shape knows where the picture goes

A picture is flat and a cube is not, so something has to say which part of the image lands where. Every vertex of a geometry (Part 3) carries a second, 2D address next to its 3D position: a pair of numbers called (u, v), each between 0 and 1. u is how far across the image to look, v is how far up. (0, 0) is the bottom-left corner of the picture and (1, 1) is the top-right. When the GPU colors a spot on the surface, it blends the UVs of the nearby vertices to find the spot's own (u, v), and grabs that pixel. This is called UV mapping, and the good news is that every built-in geometry comes with its UVs already filled in. You only need to know how the three shapes below use them, because the Target shape toggle in "Try it" switches between them.

BoxGeometry

the whole picture, six times

Each of the six faces has UVs running from (0, 0) to (1, 1), so each face shows the complete image. Paint a letter and you see it six times.

SphereGeometry

a world map on a globe

u goes once around the equator and v runs pole to pole. The picture stretches around the middle and pinches to a point at the top and bottom, exactly like a flat map of Earth wrapped onto a globe.

PlaneGeometry

the picture, once, flat

The simplest case: one copy, no distortion, exactly what you drew. Planes are how you make floors, walls, signs, and (Part 13) scoreboards.

3. Paint on it: the texture is live

Here is the part that makes textures click. The canvas is still a canvas after it becomes a texture. Draw on it again and the picture changes; the only thing three.js needs is a nudge. The texture lives in two places, your canvas in normal memory and a copy on the graphics card, and three.js does not re-send the copy every frame, because that would be slow. Setting texture.needsUpdate = true is the nudge: "the picture changed, upload it again on the next render." Forget it and you can paint all day with nothing showing on the cube.

The painting itself is a few pointer events (pointerdown, pointermove, pointerup), which fire for a mouse, a finger, and a stylus alike. One catch: the canvas is 256 pixels wide in memory but might be shown at 200 or 300 pixels on the page, so convert the pointer's screen position to canvas pixels with getBoundingClientRect before drawing.

paint.js
let brushColor = '#f8fafc';   // the swatch row sets this
let brushSize = 14;           // the Brush size slider sets this (pixels on the canvas)
let painting = false;

function paintAt(event) {
  // The canvas may be shown bigger or smaller than 256 px: convert screen → canvas pixels
  const rect = canvas.getBoundingClientRect();
  const x = (event.clientX - rect.left) * canvas.width / rect.width;
  const y = (event.clientY - rect.top) * canvas.height / rect.height;

  ctx.fillStyle = brushColor;   // a round dot of paint
  ctx.beginPath();
  ctx.arc(x, y, brushSize / 2, 0, Math.PI * 2);
  ctx.fill();

  texture.needsUpdate = true;   // THE line: the picture changed, re-send it to the GPU
}

canvas.addEventListener('pointerdown', (e) => { painting = true; paintAt(e); });
canvas.addEventListener('pointermove', (e) => { if (painting) paintAt(e); });
canvas.addEventListener('pointerup',   () => { painting = false; });
canvas.addEventListener('pointerleave', () => { painting = false; });

This is the paint canvas in "Try it." The live version also draws a short line between the previous dot and this one, so a fast swipe does not leave gaps, and the canvas has touch-action: none in its CSS so a finger paints instead of scrolling the page.

4. Repeat: one small tile, one endless floor

A game floor might be 100 meters across. You do not draw a 100-meter picture. You draw one small tile and tell the texture to repeat. Two settings do it. First, the wrap mode: texture.wrapS (the u direction) and texture.wrapT (the v direction) decide what happens when a UV goes past 1. The default, ClampToEdgeWrapping, smears the last pixel out forever. RepeatWrapping starts the picture over instead. Second, texture.repeat.set(7, 7) multiplies every UV by 7, so a surface that used to show the picture once now shows it 7 times across and 7 times up. Together, a 128-pixel tile becomes a floor of 49 tiles, at no extra cost.

Once the picture can repeat, it can also slide. texture.offset.x shifts where the picture starts, in units of whole picture widths. Add a little to it every frame, times dt so it moves the same speed on every device (Part 7), and the pattern flows across the surface: a conveyor belt, a river, the road under a driving game. The hero stage's floor is doing exactly this.

floor.js
// gridCanvas is a small 128×128 tile: navy with a tangerine grid line at the edges
const floorTexture = new THREE.CanvasTexture(gridCanvas);
floorTexture.colorSpace = THREE.SRGBColorSpace;
floorTexture.wrapS = THREE.RepeatWrapping;   // tile left-right (u). Default is ClampToEdgeWrapping
floorTexture.wrapT = THREE.RepeatWrapping;   // tile up-down (v). Set BOTH or repeat does nothing
floorTexture.repeat.set(7, 7);               // 7 × 7 copies across the plane

const floor = new THREE.Mesh(
  new THREE.PlaneGeometry(14, 14),
  new THREE.MeshStandardMaterial({ map: floorTexture })
);
floor.rotation.x = -Math.PI / 2;   // planes stand up by default; lay it flat (Part 6)
floor.position.y = -1.1;
scene.add(floor);

const SCROLL_SPEED = 0.15;   // picture-widths per second (Part 7: always × dt)
function animate() {
  const dt = Math.min(clock.getDelta(), 0.1);
  cube.rotation.y += 0.5 * dt;
  floorTexture.offset.x += SCROLL_SPEED * dt;   // slide the picture: a conveyor belt
  renderer.render(scene, camera);
}
renderer.setAnimationLoop(animate);

This is the hero stage's floor and loop. In "Try it," the Repeat slider is the 7 in repeat.set and the Scroll toggle is the offset.x line, applied to your painted texture instead of the floor.


Try It

Paint a texture

The square on the right is a real 256×256 canvas, and the shape on the left is wearing it. Pick a color, drag on the square, and watch your stroke appear on the shape as you draw. The presets redraw the whole canvas with code, like checkerboard.js does. The Repeat slider and Scroll toggle are the two ideas from floor.js, applied to your painting, and Target shape swaps the geometry so you can see how the same picture lands on a cube, a sphere, and a plane.

Paint here canvas 256×256 · drag with a mouse or finger

14 px

Nothing here is an image file. The texture on the shape is the canvas on the right, uploaded to the graphics card each time you draw.

Preset pattern redraws the whole canvas with code, like checkerboard.js
1 × 1
Target shape same picture, different UVs; old geometry is disposed
Motion and cleanup Scroll is the offset.x line from floor.js; Clear redraws the current preset over your paint
Live code: what the controls are setting
const texture = new THREE.CanvasTexture(canvas);   // 256×256, drawn on the right
texture.colorSpace = THREE.SRGBColorSpace;
texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
texture.repeat.set(1, 1);   // the picture once across, once up
texture.needsUpdate = true;   // waiting for a brush stroke or a preset…
mesh.geometry = new THREE.BoxGeometry(1.6, 1.6, 1.6);   // material: { map: texture }
// Scroll off: texture.offset.x stays at 0
  1. Pick a bright color and paint your initial on the canvas, then switch Target shape from Cube to Sphere. On the cube your letter appears on all six faces, each one the full picture. On the sphere it stretches around the middle and squeezes toward the top and bottom, and anything you painted near the top edge of the canvas gets pinched into a point at the pole. A flat picture cannot wrap a ball without distortion, and the UVs decide where the distortion goes.
  2. Choose Checkerboard and drag Repeat up to 8. The 8×8 board becomes a 64×64 board on each face: repeat.set(8, 8) multiplies every UV by 8, so each face now shows the picture 64 times. Notice the tiles get so small they start to shimmer and blur; the picture is still 256 pixels, just spread thinner. Switch to Plane to see it flat, then paint one big dot and watch it appear 64 times.
  3. Choose Stripes, set Repeat to 2, and turn on Scroll. The stripes slide around the shape like a conveyor belt. Nothing is moving except a number: texture.offset.x grows by 0.15 * dt each frame, so it slides the same speed on every device. Turn Spin off so the shape holds still, then paint a stroke and watch it ride the belt too.

Watch Out

Common mistakes

Texture bugs almost never throw an error. The object just looks wrong: too pale, stuck, stretched, or plain black. Here are the four you will hit first, and the one line that fixes each.

The texture looks washed out

Your bricks are there, but pale and chalky, as if someone turned up the brightness. The colors on the canvas looked fine.

Fix: texture.colorSpace = THREE.SRGBColorSpace;. Since r152, three.js treats a texture as linear data unless told it holds screen colors, and a picture of colors is not linear. Set this on every color texture, file or canvas.

Painted changes don't show up

You can see your strokes on the 2D canvas, but the cube keeps showing the picture from the moment it was created. Drawing more does nothing.

Fix: texture.needsUpdate = true; after every redraw. The graphics card has its own copy of the picture and three.js only re-uploads it when you ask. CanvasTexture sets this for you once, at creation, which is why the first picture always works and the second one never does.

repeat does nothing

You set texture.repeat.set(4, 4) and instead of tiles you get one small copy in the corner with its edge pixels smeared across the rest of the surface.

Fix: the wrap mode is still the default, ClampToEdgeWrapping, which stretches the last pixel when a UV passes 1. Set texture.wrapS = THREE.RepeatWrapping and texture.wrapT = THREE.RepeatWrapping. Forgetting one gives you tiles in one direction and smears in the other.

Black object after TextureLoader.load

You loaded 'images/bricks.png' and the mesh is solid black. No error in the console.

Fix: a material with a map that has not arrived yet samples an empty texture and draws black. Loading is asynchronous, so a brief black flash is normal. If it stays black, the file never came: open the browser's Network tab, find the red 404, and fix the path or host the file next to your page. Opening the .html straight from your hard drive blocks textures too; use a local server.


Your Turn

Check your understanding

You drew a scoreboard on a canvas, made it a CanvasTexture, and put it on a plane above the arena. It shows "Score: 0" perfectly. But when the player scores and you redraw the canvas with "Score: 10", the plane keeps showing 0. What one line did you forget after redrawing, and why does three.js need it?

Your answer:

Sample answer: texture.needsUpdate = true;. The canvas in memory and the copy on the graphics card are two different pictures. three.js uploaded the canvas once, when the CanvasTexture was created, and will not upload it again unless you ask, because re-sending every texture every frame would be slow. Setting needsUpdate tells it "this one changed, send it again on the next render," and the plane shows "Score: 10." Part 13 builds a whole HUD on this.


Check Yourself

Quick quiz

1. What is the difference between a material's color and its map?

2. You set texture.wrapS = texture.wrapT = THREE.RepeatWrapping and texture.repeat.set(4, 4) on a floor. What do you see?

3. What is a UV coordinate?

Keep learning

Your objects are no longer flat colors. You know that a texture is just an image on a material's map, that you can draw one with a canvas and update it live with needsUpdate, how UVs place it on a shape, and how RepeatWrapping and offset tile and scroll it. Next, the player gets to move the camera: drag to orbit, scroll to zoom, and a camera that follows a moving character.

Part of the Games and Animations with Three.js tutorial series.