JavaScript in 10 minutes
A character is a small program written in JavaScript, the language of web pages. You do not need all of it: these nine ideas are enough to change any character or to make your own. Open the Character Studio next to this page and try each one. To start from a ready character, press New character there.
1. A script is a list of instructions
The computer reads a script from the top down, and each instruction does one thing. A character has a
draw(pen, t) function for each animation. The game runs it once for every frame, and each line in
it draws a shape with the pen. Shapes drawn later go on top of shapes drawn earlier.
draw(pen, t) {
pen.circle(0, -26, 24, { fill: '#7fc8f8' }); // the body
pen.circle(-8, -32, 3, { fill: '#1d1530' }); // an eye on top of it
}
Try it: Pebble, a character with one frame
2. Numbers, text and notes
- Numbers are written plainly:
24,-8,0.5. A decimal has a dot, not a comma. -
Text goes in quotes:
'New friend'. Colours are text too.'#ff9966'is a hex code: # and then how much red, green and blue, each from00(none) toff(full). - Notes start with
//. The computer skips the rest of that line, so a note is for people. -
Random numbers:
pen.between(2, 6)picks a number from 2 up to 6. It picks the same one in every frame, so nothing jumps around.
3. Names for values: const
const gives a value a name. Use the name in many places, and change the value in one:
const BODY = '#7fc8f8';
const size = 5;
pen.circle(-10, -26, size, { fill: BODY });
pen.circle(10, -26, size, { fill: BODY });
A name is letters and digits with no spaces, and starts with a letter. Capitals count: size and
Size are different names. A name can be made only once inside the same { }, so a second
const size there is an error.
4. Lists and settings
Square brackets make a list: [-1, 1]. A point is a list of two numbers, [x, y], so a
shape with corners takes a list of points:
pen.polygon([[0, -46], [10, -30], [-10, -30]], { fill: '#f15bb5' });
Curly brackets with labels make an object: settings with names, like a form.
{ fill: '#f15bb5', line: 2 } has two settings: fill is the colour inside, and
line is how thick the outline is. A colon goes between a label and its value, and a comma between
settings.
5. Calling a command
pen.circle(0, -30, 10, { fill: '#ffd166' }) calls the pen's circle command. The values in
the round brackets are its arguments, separated by commas, and their order matters: for a circle it is x,
y, radius, then the style. The blocks below explain the arguments of each command.
In the Studio, click a shape to see its handles and drag them: the numbers in its call change for you. That
works for numbers written out, like -30. A number worked out from others, like
side * 8, has a grey handle: change it in the code.
Every (, [ and { needs its partner ), ] or
}. A semicolon ; ends an instruction.
6. Where things go
(0, 0)is the ground, right under the character's feet.- x goes right, so negative x is left.
-
y goes down, so negative y is up:
-40is 40 pixels above the ground. This surprises everyone at first. - Everything must stay inside the box,
widthwide andheighttall (dashed in the Studio). - Angles are in degrees and turn clockwise: 0 points right, 90 points down.
-
pen.group({ x, y, rotate, scale }, () => { … })moves, turns and grows all the shapes inside its{ }together.
7. Repeat and choose
for repeats lines. Here i counts 0, 1, 2, 3, and i++ adds 1 each time:
for (let i = 0; i < 4; i++) {
pen.circle(-12 + 8 * i, -14, 3, { fill: '#ffffff' });
}
for … of goes through a list. With [-1, 1] it draws a left side and a right side, like two eyes:
for (const side of [-1, 1]) {
pen.circle(side * 8, -32, 3, { fill: '#1d1530' });
}
if chooses: the lines in its { } run only when its test is true, and the lines after
else run when it is false. Tests compare numbers: < less than, > more
than, === equal; && means "and".
8. Time: t and pen.wave
In draw(pen, t), t is the time. It goes from 0 to 1 during one pass of the animation, so a
number made from t makes things move:
-
pen.wave(t)goes 0, 1, 0, −1, 0, smoothly.3 * pen.wave(t)moves something up and down by 3 pixels;pen.wave(t, 2)does it twice. Math.sin(Math.PI * t)goes from 0 up to 1 and back to 0 once: the shape of a jump.-
A loop must end where it starts, because frame 0 comes again after the last frame. So use whole numbers in
pen.wave(t, 2).
The rest of this page shows how each animation moves: idle, walk, jump and air, and then what the trail picture is.
Try it: Robo's walk, then drag the t slider
9. When it goes red
When the Studio cannot run the script, it shows a message under the code and marks the line, and the last good picture stays. The usual causes:
- a missing comma between arguments, settings or list items;
- a bracket without its partner: count the
(and the); - a quote without its partner:
'#ff9966needs a'at the end; - a name spelled differently from where it was made (
Sizeandsize).
Two mistakes do not turn red, so check them by eye. A shape outside the dashed box gets cut off in the game. A loop that does not end where it starts makes a jump at its end: drag the t slider to 1 and back to 0.
Ctrl+Z (⌘Z on a Mac) takes back the last change, even a block you added. Back to original brings back a built-in character as it was.
Blocks
Each card shows what its code draws. The Blocks box above the code in the Studio adds these to your script: click a block to add it, or its ? to read about it. A block goes where the caret is when it can go there, and otherwise into the function that draws the whole character. Then change its numbers and watch the picture.
Styles: how a shape looks
Every shape ends with a style in { }: its colours and outline. Each picture below is drawn by the code
beside it. Mix them: { fill: '#7cc4ff', line: 4, shade: true }. Shade and shine need a
#rrggbb fill.
pen.circle(0, -44, 30, { fill: '#7cc4ff' });
fill: the colour inside, as a #rrggbb code.pen.circle(0, -44, 30, { line: 4 });
fill: only the outline.pen.circle(0, -44, 30, { fill: '#7cc4ff', line: 0 });
line: 0: no outline of its own. (See Two outlines below.)pen.circle(0, -44, 30, { fill: '#7cc4ff', line: 8 });
line: how thick the outline is. Left out, it is the character's line (3).pen.circle(0, -44, 30, { fill: '#7cc4ff', ink: '#e63946' });
ink: the colour of the outline.pen.circle(0, -44, 30, { fill: '#7cc4ff', shade: true });
shade: a darker side, away from the light, so it looks round.pen.circle(0, -44, 30, { fill: '#7cc4ff', shine: true });
shine: a light spot, like a reflection.pen.circle(-12, -44, 26, { fill: '#ffd166' });
pen.circle(12, -44, 26, { fill: '#7cc4ff', alpha: 0.5 });
alpha: see-through, from 0 (invisible) to 1 (solid).pen.rect(-30, -74, 60, 60, { fill: '#c77dff', corner: 16 });
corner (rectangles only): how round the corners are.pen.circle(-10, -40, 26, { fill: '#ffd166' });
pen.circle(12, -50, 20, { fill: '#ff8fab' });
Two outlines
A character can also have a thick outer outline: silhouette: 2 at the top of its script draws one round
the whole figure, so its edge stands out. Every shape is part of that figure, even one with line: 0, so a
shape at the edge still gets the thick outline (that is how Cloud's puffs share one outline). To leave a shape out of
it, add silhouette: false; for no border at all, write { line: 0, silhouette: false }.
A see-through shape (alpha below 1) is always left out.
When each animation plays
Two games play the characters: the play field in the Test Lab, and Quiz Climb. Both find animations by name, and
only idle is required. The table shows when each name plays.
| Name | Lab play field | Quiz Climb | Plays |
|---|---|---|---|
idle |
Standing still. | Standing still. | In a loop |
walk |
Moving in any direction. | Running on the ground. | In a loop |
jump |
When you press Space. Only the character that you control jumps. | Never: the physics makes the jump. | Once |
wave |
Now and then, for the characters that you do not control. Every 2 to 5 s, each one picks a new place to go, or waves instead (about 3 times in 10). | Never. | Once |
air |
Never. | In the air, going up or coming down. | In a loop |
| any other name | Never. The Character Studio and the Test Lab show it. | Never. | – |
A missing animation shows idle instead; a missing jump or wave is never started.
The trail is not an animation: it is a small picture of its own, which both games
scatter behind a moving character.
Five rules follow from the table:
- Draw the character facing right. Both games mirror the picture when the character moves left.
- Move on the spot. The games move the character. The Test Lab's play field moves it at 150 pixels per second for you and 55 for the others, and Quiz Climb at up to 6 m/s. One walk animation serves every speed, so the feet slide a little. Short, quick steps hide the slide best.
-
In Quiz Climb, the physics jumps. Gravity and the jump speed lift the character, so
airstays on the spot, likewalk. The game also squashes the picture on landing and stretches it on take-off. -
Start close to idle. Each change of animation starts the new one at t = 0: from idle to walk, from
walk to idle, and back after a jump or a wave. If frame 0 of each animation looks like frame 0 of
idle, the character does not pop when it changes. -
An action plays once. In the Test Lab, a jump or a wave lasts frames ÷ fps seconds. Then the game goes
back to idle or walk. Give actions
loop: false, so that the last frame is t = 1 and can be the end pose.
Time: t, frames and fps
The baker calls draw(pen, t) once for each frame and keeps the picture. The game then shows
fps pictures each second, so one pass of an animation lasts frames ÷ fps seconds.
The loop setting decides which values of t the frames get:
| Loop (the default) | Once (loop: false) |
|
|---|---|---|
| t of frame i | i ÷ frames. t never reaches 1. | i ÷ (frames − 1). The last frame is t = 1. |
| 4 frames | t = 0, 0.25, 0.5, 0.75 | t = 0, 0.333, 0.667, 1 |
| Rule | t = 1 must give the same picture as t = 0, because frame 0 comes after the last frame. | t = 0 is the start pose, and t = 1 is the end pose. |
The example characters use these timings:
| Animation | frames | fps | Seconds |
|---|---|---|---|
idle |
12 to 24 | 10 to 12 | 1.2 to 2.0 |
walk |
8 to 12 | 12 to 14 | 0.67 to 1.0 |
jump |
14 to 18 | 16 to 18 | 0.78 to 1.0 |
wave |
16 to 20 | 12 to 15 | 1.33 |
air |
8 to 12 | 10 to 12 | 0.67 to 1.0 |
Idle loops are slow, so that the character looks calm. Walks and jumps are short and fast.
idle: small signs of life
A picture that never moves looks dead. An idle loop adds 2 or 3 small, slow motions, and each motion has its own timing. Keep each motion small: 1 or 2 pixels, or a few degrees.
These values change in Robo's idle:
-
Breathing:
bob = 0.5 + 0.5 * pen.wave(t)moves the upper body up and down by 1 pixel, once per loop. -
Follow-through:
antenna = 6 * pen.wave(t, 1, 0.2)is the same wave, 0.2 of a loop later. Parts that hang or stick out look loose when they move a little after the body: antennas, tails, leaves and ears. -
Blink:
eyes = t >= 0.6 && t < 0.66 ? 0 : 1shuts the eyes for one frame. Keep a blink away from t = 1, or the loop does not end where it starts.
Other ideas: squash and stretch the body (Sprout), move the pupils on a small circle with
pen.polar(1.6, 360 * t) (Octopus), or twitch an ear in a short window of t (Cat).
walk: two steps per loop
One walk loop is two steps: first the left foot, then the right foot. Most parts follow one number,
step = pen.wave(t), which goes from 0 up to 1, down to −1 and back to 0 once per loop.
These values change in Robo's walk:
-
Feet take turns:
legL = 6 * Math.max(0, step)andlegR = 6 * Math.max(0, -step).Math.max(0, …)keeps only the top half of the wave, so each foot rests while the other foot lifts. -
Legs swing:
swing = pen.wave(t, 1, 0.25)is the same wave a quarter of a loop later. The hips turn the legs byswingL = 18 * swingandswingR = -18 * swingdegrees. So a foot swings forward while it is up, and back along the ground while it is down: it goes round half an ellipse, and the legs walk instead of stamping. Feet without legs slide instead: Cat moves its left paw by4 * swingpixels and its right paw by-4 * swing. -
Body bobs:
bob = 1.5 * Math.abs(step).Math.absturns the bottom half of the wave upward, so the body rises once for each step. -
Arms swing in turn:
armL = 14 + 12 * stepandarmR = 14 - 12 * step. One arm swings out while the other swings in. -
Body rocks:
lean = 4 * steptilts the body by up to 4 degrees, to one side and then to the other. -
Follow-through:
antenna = -10 * pen.wave(t, 1, 0.12)moves a little after the body. - Eyes look ahead:
look = 2.5moves the eyes to the right, the way the character walks.
Characters without legs move the whole body. Sprout hops once per loop with
up = Math.sin(Math.PI * t) and squashes when it lands. Ghost floats with
8 + 2 * pen.wave(t, 2) and leans 8 degrees into the walk. Octopus moves its tentacle wave
twice as fast as in idle.
jump: crouch, fly, land
In the Test Lab, a jump plays once, so t goes from 0 to 1 one time. The Test Lab does not lift the character, so the animation must. Split t into 3 phases, and give each phase a number that goes from 0 to 1 while the phase runs.
These values change in Robo's jump:
-
Crouch, t from 0 to 0.15:
crouch = t < 0.15 ? Math.sin(Math.PI * t / 0.15) : 0goes 0 → 1 → 0. Robo dips by 3 pixels before it leaves the ground. -
Flight, t from 0.15 to 0.85:
flight = Math.min(1, Math.max(0, (t - 0.15) / 0.7))goes from 0 to 1 during the flight. The height4 * flight * (1 - flight)is a parabola, like the path of a thrown ball. Robo flies 30 pixels high and raises its arms with the height. -
Landing, t from 0.85 to 1:
land = t > 0.85 ? Math.sin(Math.PI * (t - 0.85) / 0.15) : 0is a second dip that takes the fall. - End on the ground: at t = 1 every value is back to 0, so the last frame is the standing pose.
The highest frame must still fit in the box, so make height big enough for the jump. Star
buddy spins once with easing, 360 * t * t * (3 - 2 * t). Dragon flaps 3 times in the air with
35 * Math.sin(2 * Math.PI * 3 * fly).
See it in the Studio: Robo Star buddy Dragon
wave: raise, wave, lower
A wave is also an action: it plays once while the character stands still. It starts right after idle, so the arm must go up first and come down again at the end.
These values change in Robo's wave:
-
Up and down:
ramp = Math.min(1, t / 0.2, (1 - t) / 0.2)climbs from 0 to 1, stays at 1, and falls back to 0. Thenup = ramp * ramp * (3 - 2 * ramp)(smoothstep) makes each move start and stop slowly. -
Waving:
armR = 6 + (144 + 18 * pen.wave(t, 2)) * up. The arm turns 144 degrees up from its rest angle of 6 and swings 18 degrees each way, twice. The swing is multiplied byup, so it is small while the arm goes up and down. -
Body:
lean = -3 * upleans back a little, andantenna = 5 * pen.wave(t, 2, 0.15) * upfollows the swing.
An arm raised sideways reaches far from the body, so make width big enough for it. To see a
wave in the game, open the Test Lab and look at the characters that you do not control. Only they wave.
See it in the Studio: Robo
air: in the air (Quiz Climb)
Quiz Climb plays air while the character is off the ground, going up or coming down. The physics
moves the character, so air is a short loop on the spot. Without it, Quiz Climb shows idle.
-
Arms up, feet tucked: Robo raises its arms to
130 ± 8 * pen.wave(t, 2)degrees and lifts both feet by 4 pixels. -
Flapping: Penguin spreads its flippers to
70 + 15 * pen.wave(t, 2)degrees, twice per loop. -
No lift: keep
air(the height above the ground) at 0, unlikejump. The game already squashes the picture on landing and stretches it on take-off.
See it in the Studio: Robo Penguin Star buddy
trail: what it leaves behind
A trail is a small picture of its own, not part of the character: a nut, a paw print, a sparkle. While the character moves, both games scatter copies of it where the character has been. Each copy drifts off in a random direction and fades away within 1 to 2 seconds. Standing still leaves nothing new.
The game does the moving and the fading, so your script draws only the picture. It goes next to
animations, not inside them:
animations: { … },
trail: { width: 12, height: 12, frames: 8, fps: 12, draw: (pen, t) => nut(pen, t) },
-
Its own small box:
widthandheight, at most 48. As for the character, (0, 0) is the middle of the box's bottom, so the picture stays within x from −width/2 to width/2 and y from −height to 0. -
A loop or a still picture:
frames: 1draws one still picture. With more frames it plays as a loop, so it must end where it starts, asidledoes. -
Thin lines: a picture this small turns into a dark blob with a thick outline. Use
line: 1orline: 0.
Every example character has one. Some of them:
- Robo's nut spins:
rotate: 360 * tturns it once per loop, so the loop closes. -
Cat's paw print is still:
frames: 1. Its toes sit on a circle round the pad, atpen.polar(7, a)for a = −130°, −90° and −50°. -
Tomato's sparkle twinkles: its size follows
Math.exp(-K * age)withage = t % 1, the same exponential decay as the sparkles around its body.% 1makes t = 1 the same as t = 0, so the loop closes. -
Rainbow Drop's dot changes colour:
hsl(360 * t, SAT, LIGHT)takes it once round the colour wheel; 360° is red again, as at 0°.
See it in the Studio: Robo Cat Tomato Rainbow Drop
Other animation names
An animation can have any name but trail (that name is the trail picture's
own setting), for example to try an idea. The Character Studio and the Test Lab show every animation, but the
games play only the names above. The examples have three more:
-
Ghost
boo: plays once. The ghost swells and shouts withswell = Math.sin(Math.PI * t). -
UFO
beam: a loop. The beam grows and shrinks with0.5 - 0.5 * Math.cos(2 * Math.PI * t). -
Cloud
rain: a loop. Drop i falls with(2 * t + i * 0.37) % 1.
For programmers: to play one in the game, start it like the jump in src/app/field.ts, with
startAction('boo') on a key.
Motion shapes
Most motion is built from a few formulas. Each one turns t into a number with a useful shape. Multiply the number by a size, and add it to a position or an angle.
pen.wave(t): back and forth once per loop. Breathing, swaying.pen.wave(t, 2): twice per loop. Use a whole number of cycles, or the loop does not close.
pen.wave(t, 1, 0.2): the same wave, 0.2 of a loop later. Parts that follow the body.
Math.abs(pen.wave(t)): two bumps per loop. A bob on each step.Math.max(0, pen.wave(t)): only the top half. A foot that lifts and then rests.
Math.sin(Math.PI * t): 0 → 1 → 0 once. A hop, or a swell in an action.4 * t * (1 - t): a parabola. The height of a thrown ball.t * t * (3 - 2 * t): smoothstep, from 0 to 1 with a slow start and a slow end. Spins and
arm moves.
Math.min(1, Math.max(0, (t - a) / (b - a))): 0 until a, then up to 1 at b. One phase of an
action (here a = 0.2, b = 0.6).
t >= a && t < b: true only in a short window. A blink (here a = 0.6, b =
0.66).
(2 * t + offset) % 1: from 0 to 1, then back to 0, twice per loop. Things that fall or
repeat.
Check your animation
-
In the Studio, pick the animation under the picture and drag t. Turn on Snap to frames to
see the frames that the baker keeps, and press Play to see the speed. Add
pen.watch('name', value)to show a number under the timeline. -
Run the tests:
npm testdraws every frame of each character incharacters/cast.json. A test fails when a shape leaves the box, when a loop does not end where it starts, or when a jump does not land. The trail picture is checked the same way, in its own small box. -
See every frame at once:
npm run render -- characters/03-robo.jswritesrenders/03-robo.png, with each frame, its t, the box and the ground line. Add--anim walk --scale 3to see one animation bigger. - Play it in the Test Lab: walk with the arrow keys or W A S D, press Space to jump, and watch the other characters wave. Then try it in Quiz Climb, where it walks, jumps and flies.