WEEK 03

Web Games Development · HTML5 Lab

Animation, Inputs & Media

Animate with timers, bounce a ball off walls, read player input, and mix in images, gradients and video.

setInterval

collisions

form input

images & video

Book: Chapter 3 · Bouncing Ball · pp. 67–96

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 files25 min
1:25Build-your-own task, recap and exit quiz5 min

Week 3 · Animation, Inputs & Media

2 / 35

Warm-up · 5 minutes

Remember Week 2?

1

Write the formula for a random die value 1–6.

2

Where is (0, 0) on a canvas?

3

Which method draws a circle?

4

What does the variable firstturn remember?

Week 3 · Animation, Inputs & Media

3 / 35

This week’s game

A ball bouncing in a box

A ball moves around a box and bounces off the walls. The player types new horizontal and vertical speeds into a form.

The book builds three versions: a ball drawn with code, an image ball with gradient-coloured walls, and a form that checks its own input.

This is computed animation: the position is recalculated and redrawn at fixed intervals. Cel animation, such as an animated GIF, shows pictures drawn in advance.

FROM THE BOOK

Chapter 3 · Bouncing Ball
pp. 67–96


YOU WILL BUILD

  • bouncingballinputs.html
  • bouncingballinputsvalidate.html
  • bouncingcandybackground.html
  • bouncintballinputsimggradients.html
  • bouncingVideoOk2.html

Week 3 · Animation, Inputs & Media

4 / 35

Objectives

By the end of Week 3 you can…

01

Repeat code over time with setInterval; stop it with clearInterval.

02

Erase and redraw the canvas every frame so motion looks smooth.

03

Represent motion with a position and a velocity.

04

Detect collisions with the walls and reverse the velocity.

05

Read numbers from form fields with Number().

06

Use HTML5 input validation: type="number", min, max.

07

Draw images with drawImage and embed video with <video>.

Week 3 · Animation, Inputs & Media

5 / 35

Key words this week

Vocabulary

TermMeaning
animationPictures shown fast enough to look like movement
frameOne redraw of the scene
setIntervalCalls a function again and again, every N milliseconds
clearIntervalStops a timer started by setInterval
velocityHow far the ball moves each frame: ballvx, ballvy
collisionWhen the ball would reach or pass a wall
validationChecking input before it is used
gradientA smooth blend between colours

Week 3 · Animation, Inputs & Media

6 / 35

What the program must do

What a bouncing ball needs

A timer

Code runs at short, fixed intervals so the result looks like motion.

Virtual walls

There is no real ball or wall: compare positions and reverse the speed on a hit.

Player input

Form fields now send values in. In Week 2 they only showed results.

Robust input

Do not act on bad entries, and show the player which field is wrong.

Week 3 · Animation, Inputs & Media

7 / 35

Big idea 1 · The animation loop

Animation = erase, move, draw, repeat

1

Erase

clearRect wipes the box.

2

Move

moveandcheck works out the new position.

3

Draw

arc and fill paint the ball again.

Week 3 · Animation, Inputs & Media

8 / 35

Example 1 · The animation loop

Erase, move, draw, repeat

setInterval calls a function again and again. Each call draws one frame of the animation.

CODE · script · canvas 400 × 200

var x = 20;
function frame() {
  ctx.clearRect(0, 0, 400, 200);   // erase
  x = x + 4;                       // move
  if (x > 400) x = 0;
  ctx.beginPath();
  ctx.arc(x, 100, 20, 0, 2 * Math.PI);
  ctx.fill();                      // draw
}
setInterval(frame, 30);

OUTPUT · running live

Week 3 · Animation, Inputs & Media

9 / 35

Line by line · Example 1

Erase, move, draw, repeat

var x = 20;

The ball’s position, remembered between frames.

ctx.clearRect(0, 0, 400, 200);

Wipe the previous frame.

x = x + 4;

Move 4 pixels to the right.

if (x > 400) x = 0;

Off the right edge? Start again at the left.

setInterval(frame, 30);

Run frame every 30 ms: about 33 frames a second.

Week 3 · Animation, Inputs & Media

10 / 35

Try it · 5 minutes

Feel the frame rate

  1. Change 100 to 20, then to 500.
  2. Remove the clearRect line and watch.
  3. Put clearRect back.

YOU SHOULD SEE

20 is smooth and 500 is jerky. Without clearRect the ball leaves a trail.

Week 3 · Animation, Inputs & Media

11 / 35

Big idea 2 · Collision & bouncing

Check first, then move

1

Predict

nballx = ballx + ballvx

2

Test

Past a wall? Flip the sign of the velocity.

3

Commit

ballx = nballx

Week 3 · Animation, Inputs & Media

12 / 35

Example 2 · Collision & bouncing

Reverse the velocity at a wall

Velocity is how far the ball moves each frame. Hitting a wall flips its sign.

CODE · script · canvas 400 × 200

var x = 50, y = 50, vx = 5, vy = 3;
function frame() {
  ctx.clearRect(0, 0, 400, 200);
  x = x + vx;
  y = y + vy;
  if (x > 380 || x < 20) vx = -vx;  // sides
  if (y > 180 || y < 20) vy = -vy;  // top, bottom
  ctx.beginPath();
  ctx.arc(x, y, 20, 0, 2 * Math.PI);
  ctx.fill();
}
setInterval(frame, 30);

OUTPUT · running live

Week 3 · Animation, Inputs & Media

13 / 35

Line by line · Example 2

Reverse the velocity at a wall

vx = 5, vy = 3

Speed: 5 px right and 3 px down per frame.

x = x + vx;

Move by the velocity.

x > 380 || x < 20

Past the right OR left wall (radius 20).

vx = -vx;

Flip the direction: 5 becomes −5.

y > 180 || y < 20

The same test for the floor and ceiling.

Week 3 · Animation, Inputs & Media

14 / 35

Try it · 5 minutes

Change the box

  1. Make the box wider.
  2. Make the ball radius bigger.
  3. Predict first: will the ball still touch the walls exactly?

YOU SHOULD SEE

Yes: the bounds are worked out from the box size and the radius, so the bounce stays accurate.

Week 3 · Animation, Inputs & Media

15 / 35

Big idea 3 · Input & validation

Input → check → use

1

Input

The player types a speed and presses CHANGE.

2

Check

type, min and max; bad entries turn red.

3

Use

Number() turns the text into a number.

Week 3 · Animation, Inputs & Media

16 / 35

Example 3 · Input & validation

Check input before you use it

HTML5 can check number fields for you, and Number() turns field text into a real number.

CODE · input.html

<style>
  input:valid   { background: palegreen; }
  input:invalid { background: salmon; }
</style>
<input type="number" min="0" max="10" value="4">
<input type="number" min="0" max="10" value="20">
<p id="out"></p>
<script>
  var t = "7";                    // field text
  document.getElementById("out").textContent =
    (t + 1) + " vs " + (Number(t) + 1);
</script>

OUTPUT · rendered by the browser

Week 3 · Animation, Inputs & Media

17 / 35

Line by line · Example 3

Check input before you use it

type="number" min="0" max="10"

Only numbers from 0 to 10 are valid.

input:valid { … }

Style for a field whose value is allowed.

input:invalid { … }

Style for a field whose value breaks a rule.

t + 1

Text + 1 joins: "7" + 1 is "71".

Number(t) + 1

Convert first, then add: 7 + 1 is 8.

Week 3 · Animation, Inputs & Media

18 / 35

Try it · 5 minutes

Break it on purpose

  1. Type 20 in a box, then abc.
  2. Remove Number() and enter 3.
  3. Put Number() back.

YOU SHOULD SEE

20 and abc turn red and are blocked. Without Number(), 3 is treated as text and the movement goes wrong.

Week 3 · Animation, Inputs & Media

19 / 35

Big idea 4 · Gradients & images

Three ways to add media

1

drawImage

A picture drawn on the canvas.

2

Gradient

Colours blended across a shape.

3

<video>

A player on the page, in several formats.

Week 3 · Animation, Inputs & Media

20 / 35

Example 4 · Gradients & images

Blend colours and stamp pictures

A gradient works like a colour. drawImage stamps a picture at any place and size.

CODE · script · canvas 400 × 200

var g = ctx.createLinearGradient(0, 0, 400, 0);
g.addColorStop(0, "crimson");
g.addColorStop(1, "royalblue");
ctx.fillStyle = g;
ctx.fillRect(0, 0, 400, 60);       // gradient wall
// a small picture, drawn once...
var pic = document.createElement("canvas");
pic.width = pic.height = 40;
var p = pic.getContext("2d");
p.fillStyle = "gold"; p.fillRect(0, 0, 40, 40);
// ...then stamped at different sizes
ctx.drawImage(pic, 20, 100, 40, 40);
ctx.drawImage(pic, 100, 80, 80, 80);

OUTPUT · canvas 400 × 200, shown enlarged

Week 3 · Animation, Inputs & Media

21 / 35

Line by line · Example 4

Blend colours and stamp pictures

createLinearGradient(0, 0, 400, 0)

A gradient running left to right.

addColorStop(0, "crimson")

Colour at the start (0) of the gradient.

addColorStop(1, "royalblue")

Colour at the end (1).

ctx.fillStyle = g;

Use the gradient like a colour.

drawImage(pic, x, y, w, h)

Draw a picture at (x, y), scaled to w × h.

Week 3 · Animation, Inputs & Media

22 / 35

Try it · 5 minutes

Make it yours

  1. Use your own photo as the ball.
  2. Change the colours in the hue array.
  3. Stop and resume the candy animation.

YOU SHOULD SEE

Your photo bounces inside walls in your own colours.

Week 3 · Animation, Inputs & Media

23 / 35

Common mistakes

When it goes wrong, check these first

The ball does not move

Fix: setInterval never runs: check onLoad="init();" is on the body tag.

The ball escapes the box

Fix: Check the > and < signs, and flip with -ballvx or -ballvy.

The page reloads on CHANGE

Fix: Use onSubmit="return change();" and end change() with return false.

An image or video is missing

Fix: Put the media in the Week3 folder and match the file name exactly.

Week 3 · Animation, Inputs & Media

24 / 35

Check your understanding · 1 of 4

setInterval(moveball, 100) means…

A

Run once after 100 ms

B

Run every 100 ms

C

Run 100 times

D

Wait 100 seconds

Week 3 · Animation, Inputs & Media

25 / 35

Check your understanding · 2 of 4

The ball passes the right wall. What changes?

A

ballx = 0

B

ballvx = -ballvx

C

ballvy = 0

D

clearInterval

Week 3 · Animation, Inputs & Media

26 / 35

Check your understanding · 3 of 4

Why write Number(document.f.hv.value)?

A

To validate it

B

Form values are text

C

To round it

D

To colour it

Week 3 · Animation, Inputs & Media

27 / 35

Check your understanding · 4 of 4

Why list several <source> files in <video>?

A

To play them all

B

Browsers support different formats

C

Better quality

D

For subtitles

Week 3 · Animation, Inputs & Media

28 / 35

Check your understanding

Answers

QAnswerWhy
Q1B · Run every 100 msIt repeats until clearInterval stops it.
Q2B · ballvx = -ballvxReversing the horizontal velocity makes it bounce.
Q3B · Form values are textText would be joined, not added: "1" + "3" is "13".
Q4B · Browsers support different formatsThe browser plays the first format it supports.

Week 3 · Animation, Inputs & Media

29 / 35

Lab time · 25 minutes

Your workflow for every file

1

Folder

Create a folder named Week3.

2

Copy

Copy the example files and their images, audio or video into it.

3

Open

Open the folder in VS Code or Sublime Text.

4

Save

Edit, then save with Ctrl+S.

5

Check

Refresh the browser (F5). Open the console (F12).

Never edit the original example for grading. Work on a copy named with your name, for example bouncingballinputs_yourname.html.

Week 3 · Animation, Inputs & Media

30 / 35

Lab activity · Week3 folder

Five versions of the bouncing ball

FileObjectivesCheckpoint
bouncingballinputs.html1–5Ball bounces; the form changes its speed
bouncingballinputsvalidate.html6Bad input turns red and is blocked
bouncingcandybackground.html1, 2, 7Candy bounces over a photo; STOP and RESUME work
bouncintballinputsimggradients.html2, 3, 7Pearl image moves inside rainbow walls
bouncingVideoOk2.html2, 7A video plays on the page with the animation

Week 3 · Animation, Inputs & Media

31 / 35

Stuck?

A five-step debugging checklist

  1. Open the console (F12) and read the first red error.
  2. Check the spelling and capitals of every name and id.
  3. Check that brackets, braces and quotes come in pairs.
  4. Check file names, and that every file is in the same folder.
  5. Save, then hard-refresh with Ctrl+F5.

THIS WEEK’S TIP

Press STOP, then type ballx and ballvx in the console to see where the ball really is.

Week 3 · Animation, Inputs & Media

32 / 35

BUILD YOUR OWN · ALL OBJECTIVES

Add gravity to the ball

Week3\bouncingballinputs_yourname.html

Week 3 · Animation, Inputs & Media

33 / 35

How the build-your-own task is marked

Marking guide

CriterionWhat we look forMarks
Runs cleanlyOpens with no errors in the console (F12)2
Required featuresGravity added (ballvy grows every frame); the bounce still works; tested with several speeds4
Readable codeIndented, sensible names, a comment on each function2
Your own touchA personal change: colours, images, text or an extra feature2
Total10

Week 3 · Animation, Inputs & Media

34 / 35

RECAP · CHAPTER 3 · BOUNCING BALL SUMMARY

What you can do now

  • setInterval to set up a timing event for animation.
  • Validation of form input.
  • Functions that reposition a circle or an image.
  • Tests for virtual collisions with the walls.
  • Drawing rectangles, images and circles, including gradients.

NEXT WEEK

Week 4 · Objects & Physics

Cannonball and slingshot: gravity, angles, lists of objects and dragging with the mouse.

Week 3 · Animation, Inputs & Media

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”.