WEEK 13

Web Games Development · 3D with Three.js

Textures, Sound & HUD

Canvas textures, Web Audio sound effects and an HTML HUD: build a polished shooting gallery.

CanvasTexture

repeat

uv

Web Audio

HUD

Game: Target Range

Today · 90 minutes

Plan for the session

StartSegmentTime
0:00Warm-up review10 min
0:10This week’s game and objectives10 min
0:20Concepts: idea, code, line by line, try it35 min
0:55Common mistakes and check your understanding5 min
1:00Lab: build the game25 min
1:25Build-your-own task, recap and exit quiz5 min

Week 13 · Textures, Sound & HUD

2 / 35

Warm-up · 5 minutes

Remember Weeks 2 and 11?

1

Which canvas method draws a circle?

2

What does raycaster.intersectObjects give you for each hit?

3

Why do mouse y coordinates need a minus sign in 3D?

4

When are you allowed to play sound in a web page?

Week 13 · Textures, Sound & HUD

3 / 35

This week’s game

Aim for the yellow

Bullseye targets slide along three rails at different distances and speeds. Click to shoot where the crosshair is.

The yellow centre scores 10, the red rings 5, the outer ring 2 and the wooden edge 1. Hit targets fall flat for two seconds.

You have six shots, then press R to reload. Every sound and every texture is made in code: there are no image or audio files.

HOW TO PLAY

Click to start and to shoot.
R to reload, M to mute.


YOU WILL BUILD

  • targetRange.html
  • package.json

Week 13 · Textures, Sound & HUD

4 / 35

Objectives

By the end of Week 13 you can…

01

Paint textures on a canvas; use CanvasTexture.

02

Repeat textures with wrapS, wrapT and repeat.

03

Score by where the ray hit: hit.uv.

04

Make sound effects with Web Audio.

05

Unlock audio on the first click.

06

Build an HTML HUD over the 3D canvas.

07

Place popups with Vector3.project.

08

Add game feel: ammo, reload, recoil.

Week 13 · Textures, Sound & HUD

5 / 35

Key words this week

Vocabulary

TermMeaning
textureAn image wrapped onto the surface of a shape
CanvasTextureA texture made from a 2D canvas
uvA position on a texture, from (0, 0) to (1, 1)
RepeatWrappingTile the texture instead of stretching it
AudioContextThe browser’s sound system
oscillatorMakes a tone at a set frequency
gainVolume; a fading gain makes a short sound
HUDHeads-up display: score, ammo, timer on screen

Week 13 · Textures, Sound & HUD

6 / 35

What the program must do

What makes a game feel finished

Looks

Textured targets, a wooden floor and a sky.

Sound

A bang, a ding and a click for every action.

Information

Score, time and ammo always visible.

Feel

Popups, recoil and a reload to manage.

Week 13 · Textures, Sound & HUD

7 / 35

Big idea 1 · Canvas textures

Your 2D canvas skills paint 3D objects

1

draw

A hidden <canvas>: arc, fillRect, fillText…

2

CanvasTexture

Turn the canvas into a texture.

3

map

Give it to a material: it wraps the shape.

Week 13 · Textures, Sound & HUD

8 / 35

Example 1 · Canvas textures

A 3D die painted with canvas

The same drawing code as Week 2’s dice: one canvas painted on every face of a cube.

CODE · canvasTexture.html

const c = document.createElement("canvas");
c.width = 128; c.height = 128;
const ctx = c.getContext("2d");
ctx.fillStyle = "#ffffff";
ctx.fillRect(0, 0, 128, 128);
ctx.fillStyle = "#d62828";
[[32, 32], [96, 32], [64, 64], [32, 96], [96, 96]].forEach(function (p) {
  ctx.beginPath();
  ctx.arc(p[0], p[1], 12, 0, Math.PI * 2);
  ctx.fill();
});
const tex = new THREE.CanvasTexture(c);
tex.colorSpace = THREE.SRGBColorSpace;
const die = new THREE.Mesh(new THREE.BoxGeometry(1.5, 1.5, 1.5),
  new THREE.MeshStandardMaterial({ map: tex }));

OUTPUT · a cube wearing a canvas-drawn dice face

Week 13 · Textures, Sound & HUD

9 / 35

Line by line · Example 1

A 3D die painted with canvas

document.createElement("canvas")

A canvas in memory; it is never added to the page.

ctx.arc(…); ctx.fill()

Ordinary 2D drawing, exactly as in Weeks 2–6.

new THREE.CanvasTexture(c)

Turn the drawing into a texture.

tex.colorSpace = THREE.SRGBColorSpace

Keep the colours the same as on the canvas.

{ map: tex }

The material wraps the texture over the shape.

Week 13 · Textures, Sound & HUD

10 / 35

Try it · 5 minutes

Your own target

  1. In targetTexture(), change the ring colours.
  2. Add ctx.fillText("10", 112, 136) in the middle.
  3. Use ctx.font = "bold 32px Arial" first.

YOU SHOULD SEE

Your own colours on every target, with a “10” in the centre.

Week 13 · Textures, Sound & HUD

11 / 35

Big idea 2 · Repeat and wrap

One small tile can cover a huge floor

1

wrap

RepeatWrapping: keep tiling past the edge.

2

repeat

repeat.set(6, 12): 6 across, 12 along.

3

offset

Slide the texture: moving water, conveyor belts.

Week 13 · Textures, Sound & HUD

12 / 35

Example 2 · Repeat and wrap

Tile it, then slide it

The repeat count grows and shrinks; the offset makes the pattern flow.

CODE · repeat.html

const tex = new THREE.CanvasTexture(checkerCanvas);
tex.colorSpace = THREE.SRGBColorSpace;
tex.wrapS = THREE.RepeatWrapping;     // across (u)
tex.wrapT = THREE.RepeatWrapping;     // along (v)
tex.repeat.set(4, 4);

// in the loop:
tex.offset.y += 0.3 * dt;             // a moving floor
const n = 2 + Math.round((Math.sin(t) + 1) * 3);
tex.repeat.set(n, n);

OUTPUT · a checker texture repeating and scrolling

Week 13 · Textures, Sound & HUD

13 / 35

Line by line · Example 2

Tile it, then slide it

tex.wrapS = THREE.RepeatWrapping

Repeat across the width (the u direction).

tex.wrapT = THREE.RepeatWrapping

Repeat along the height (the v direction).

tex.repeat.set(4, 4)

Fit 4 copies across and 4 along.

tex.offset.y += 0.3 * dt

Slide the pattern: it seems to flow.

(no wrap) = ClampToEdgeWrapping

The default: the edge pixels just stretch.

Week 13 · Textures, Sound & HUD

14 / 35

Try it · 5 minutes

A moving floor

  1. In Target Range, keep the floor texture in a variable.
  2. In the loop, add floorTex.offset.y -= 0.2 * dt.
  3. Try repeat.set(3, 6): bigger planks.

YOU SHOULD SEE

Wide planks gliding towards you, like a conveyor-belt shooting range.

Week 13 · Textures, Sound & HUD

15 / 35

Big idea 3 · Sound with Web Audio

Make sounds from numbers

1

oscillator

A tone: frequency (pitch) and wave type.

2

gain

The volume, faded out quickly: a short “beep”.

3

destination

Connect to the speakers, start, then stop.

Week 13 · Textures, Sound & HUD

16 / 35

Example 3 · Sound with Web Audio

A beep is a fading wave

The live output shows what beep() makes: a wave whose volume dies away fast. (Slides cannot play sound.)

CODE · targetRange.html · beep()

let audio = null;
function initAudio() {            // call from the first click
  if (!audio) audio = new AudioContext();
  if (audio.state === "suspended") audio.resume();
}
function beep(freq, duration, type, volume) {
  const osc = audio.createOscillator();
  const gain = audio.createGain();
  osc.type = type;                // "sine", "square", …
  osc.frequency.value = freq;     // 880 = a high A
  gain.gain.setValueAtTime(volume, audio.currentTime);
  gain.gain.exponentialRampToValueAtTime(
    0.001, audio.currentTime + duration);
  osc.connect(gain).connect(audio.destination);
  osc.start();
  osc.stop(audio.currentTime + duration);
}

OUTPUT · a sine wave fading out: the shape of a beep

Week 13 · Textures, Sound & HUD

17 / 35

Line by line · Example 3

A beep is a fading wave

new AudioContext()

The sound system; only allowed after a click.

audio.createOscillator()

A tone generator: set type and frequency.

gain.gain.exponentialRampToValueAtTime(0.001, …)

Fade the volume to almost nothing.

osc.connect(gain).connect(audio.destination)

Tone → volume → speakers.

osc.start(); osc.stop(t)

Play now, stop when the fade is done.

Week 13 · Textures, Sound & HUD

18 / 35

Try it · 5 minutes

Design a sound

  1. Change the hit sound to beep(440, 0.3, "sawtooth", 0.2).
  2. Play a second, higher beep 0.1 s later with setTimeout.
  3. Which sounds most like a reward?

YOU SHOULD SEE

Two rising notes sound like a “ding-ding” reward; a single low sawtooth sounds like a buzzer.

Week 13 · Textures, Sound & HUD

19 / 35

Big idea 4 · HUD and popups

Text belongs in HTML, on top of the 3D

1

HUD

Absolutely positioned divs over the canvas.

2

project

point.project(camera): 3D → −1…+1 on screen.

3

pixels

Convert to left / top pixels, the reverse of Week 11.

Week 13 · Textures, Sound & HUD

20 / 35

Example 4 · HUD and popups

Labels that follow 3D objects

Each frame, each ball’s position is projected to the screen and its HTML label moved there.

CODE · targetRange.html · popup()

function popup(text, point) {
  const p = point.clone().project(camera);   // -1..+1
  const div = document.createElement("div");
  div.className = "popup";
  div.textContent = text;
  div.style.left = ((p.x + 1) / 2 * window.innerWidth) + "px";
  div.style.top = ((1 - p.y) / 2 * window.innerHeight) + "px";
  document.body.appendChild(div);
  requestAnimationFrame(function () {         // float up and fade
    div.style.transform = "translate(-50%, -150%)";
    div.style.opacity = "0";
  });
  setTimeout(function () { div.remove(); }, 900);
}

OUTPUT · HTML labels pinned to moving 3D balls

Week 13 · Textures, Sound & HUD

21 / 35

Line by line · Example 4

Labels that follow 3D objects

point.clone().project(camera)

Where the point appears on screen, as −1…+1.

(p.x + 1) / 2 * window.innerWidth

−1 → 0 px, +1 → the right edge.

(1 - p.y) / 2 * window.innerHeight

Flip y: screen pixels grow downwards.

div.style.transform = "translate(…)"

A CSS transition does the float-up animation.

setTimeout(() => div.remove(), 900)

Remove the popup when it has faded.

Week 13 · Textures, Sound & HUD

22 / 35

Try it · 5 minutes

Bigger, better popups

  1. Make 10-point popups red and 40px.
  2. Add the word “BULLSEYE!” for a 10.
  3. Change 900 ms to 1500 ms.

YOU SHOULD SEE

Bullseyes shout a big red “BULLSEYE! +10” that lingers a little longer.

Week 13 · Textures, Sound & HUD

23 / 35

Common mistakes

When it goes wrong, check these first

Textures look washed out

Fix: Set tex.colorSpace = THREE.SRGBColorSpace on colour textures.

The floor texture is one blurry plank

Fix: Set wrapS and wrapT to RepeatWrapping, then tex.repeat.set(…).

No sound at all

Fix: Create or resume the AudioContext inside a click handler; check M (mute) is off.

Popups appear in the wrong place

Fix: Use project(camera) on a clone of the hit point, and flip y with (1 − p.y).

Week 13 · Textures, Sound & HUD

24 / 35

Check your understanding · 1 of 4

Which class turns a 2D canvas into a texture?

A

TextureLoader

B

CanvasTexture

C

ImageBitmap

D

Sprite

Week 13 · Textures, Sound & HUD

25 / 35

Check your understanding · 2 of 4

hit.uv is (0.5, 0.5). Where did the shot land on the target face?

A

On the edge

B

In the exact centre

C

Outside the target

D

On the back

Week 13 · Textures, Sound & HUD

26 / 35

Check your understanding · 3 of 4

Why is the AudioContext created inside pointerdown?

A

It is faster

B

Browsers only allow sound after the user interacts

C

Web Audio needs the mouse position

D

To save memory

Week 13 · Textures, Sound & HUD

27 / 35

Check your understanding · 4 of 4

What does point.project(camera) return?

A

Pixels

B

A position from −1 to +1 on the screen

C

A ray

D

A colour

Week 13 · Textures, Sound & HUD

28 / 35

Check your understanding

Answers

QAnswerWhy
Q1B · CanvasTexturenew THREE.CanvasTexture(canvas).
Q2B · In the exact centreThe middle of a texture is (0.5, 0.5).
Q3B · Browsers only allow sound after the user interactsThe autoplay rule blocks sound until a click or key press.
Q4B · A position from −1 to +1 on the screenNormalised screen coordinates, which we convert to pixels.

Week 13 · Textures, Sound & HUD

29 / 35

Lab time · 25 minutes

Your workflow for 3D files

1

Folder

Create a folder named Week13 and open it in VS Code.

2

Install

In the terminal: npm init -y, npm install three, npm install -D vite.

3

Run

npx vite starts the dev server. Leave it running.

4

Open

http://localhost:5173/ plus the file name, e.g. /first3d.html.

5

Check

Save with Ctrl+S; the page reloads. Open the console (F12).

Each week is an npm project: Vite finds “three” in node_modules, so a double-clicked file shows a blank page. Build the four example files first, then the game; work on a copy named targetRange_yourname.html.

Week 13 · Textures, Sound & HUD

30 / 35

Lab activity · targetRange.html

Build Target Range in nine stages

StepObjectivesCheckpoint
Scaffold + HUD styles6Crosshair and HUD text, no errors
Scene, camera, light—A black window
Canvas + bullseye texture1Ready to paint targets
Planks, sky and floor1, 2A wooden floor under a sunset
Targets on rails1Targets slide and wrap round
Sound effects4, 5Ready to make noise
HUD + popups6, 7Ammo dots in the corner
Shooting3, 5, 7, 8Hits score, ding and pop up
Game state + loop8Timer, reload and recoil

Week 13 · Textures, Sound & HUD

31 / 35

Stuck?

A five-step 3D debugging checklist

  1. Open the console (F12) and read the first red error.
  2. Blank page? Check npx vite is running and you opened http://localhost:5173/…, not the file itself.
  3. “Failed to resolve import three”? Run npm install in the week folder.
  4. Check the spelling and capitals: THREE.BoxGeometry, not THREE.boxGeometry.
  5. Nothing visible? Check the camera is not inside or behind the object.

THIS WEEK’S TIP

To check a texture, put it on a big flat plane in front of the camera: new THREE.Mesh(new THREE.PlaneGeometry(4, 4), new THREE.MeshBasicMaterial({ map: tex })).

Week 13 · Textures, Sound & HUD

32 / 35

BUILD YOUR OWN · ALL OBJECTIVES

Make it yours: bonus target, combos, music

Week13\targetRange_yourname.html

Week 13 · Textures, Sound & HUD

33 / 35

How the build-your-own task is marked

Marking guide

CriterionWhat we look forMarks
Runs cleanlyRuns with npx vite with no console errors2
Required featuresBonus target with its own texture; working combo4
Readable codeIndented, sensible names, a comment on each function2
Your own touchYour own textures, sounds or HUD design2
Total10

Week 13 · Textures, Sound & HUD

34 / 35

Recap · Week 13

What you can do now

  • Draw with the 2D canvas → CanvasTexture → material.map.
  • RepeatWrapping + repeat for tiles; colorSpace for true colours.
  • hit.uv tells you where on a texture a ray landed.
  • Web Audio: oscillator → gain → destination, after a click.
  • HUD in HTML; project(camera) turns 3D points into pixels.

NEXT WEEK

Week 14 · Final Project: Endless Runner

Game states, spawning and object pooling, difficulty curves and fog: put everything together.

Week 13 · Textures, Sound & HUD

35 / 35

Keyboard
→ Space next   ← previous   Home/End first / last
F full screen   N speaker notes   P print / save as PDF
Click the right or left half of a slide to move forward or back.

Save as PDF: press P, choose “Save as PDF”, and turn on “Background graphics”.