TExcelTAD
Home › 2D Games with JavaScript & Canvas › Kaplay (Kaboom)

Kaplay (Kaboom)

Kaplay is a small JavaScript game library built for speed of creation: a playable prototype often fits in 50 lines. It is the community-maintained continuation of Kaboom.js (Replit's library, which stopped being developed in 2024), so Kaboom tutorials mostly still apply. Kaplay is popular for game jams, teaching and small web games.

Its big idea is composition: a game object is a list of components (position, sprite, collision area, physics body, health...) plus tags (plain strings such as 'enemy'). You don't write classes; you assemble objects from parts.

A Kaplay platformer

Install it with npm install kaplay in a Vite project. By default kaplay() puts its functions (add, pos, rect...) in the global scope, which keeps game code short:

js
import kaplay from 'kaplay';

kaplay({ width: 480, height: 270, letterbox: true, background: [14, 16, 24] });
setGravity(1400);
// loadSprite('hero', 'sprites/hero.png');   // real projects load images like this

scene('game', () => {
  const player = add([
    rect(16, 16), color(255, 183, 77),   // looks: a coloured rectangle (or sprite('hero'))
    pos(40, 100),                        // position
    area(),                              // collision shape (from the rect)
    body(),                              // gravity, jumping, solid collisions
    'player',                            // a tag
  ]);

  // solid platforms
  add([rect(480, 20), pos(0, 250), area(), body({ isStatic: true }), color(60, 70, 110)]);
  add([rect(120, 12), pos(180, 190), area(), body({ isStatic: true }), color(60, 70, 110)]);

  // coins
  for (const x of [100, 230, 380]) add([circle(5), pos(x, 160), area(), color(255, 213, 79), 'coin']);

  let score = 0;
  const label = add([text('Score: 0', { size: 14 }), pos(8, 8), fixed()]);   // fixed(): ignores the camera

  onKeyDown('left', () => player.move(-160, 0));      // move() is in pixels per second
  onKeyDown('right', () => player.move(160, 0));
  onKeyPress('space', () => { if (player.isGrounded()) player.jump(520); });

  player.onCollide('coin', (coin) => {
    destroy(coin);
    score += 1;
    label.text = `Score: ${score}`;
  });

  player.onUpdate(() => { if (player.pos.y > 400) go('game'); });   // fell off: restart the scene
});

go('game');

Read it like a list of facts about the world, not a loop: "the player has an area and a body", "when the player collides with a coin, do this". Kaplay runs the loop, gravity, collision resolution and drawing for you.

Kaplay What it does The raw-canvas version in this course
kaplay({...}) Creates the canvas, loop and input The play kit
add([...]) Creates a game object from components Object literals in arrays
pos(), rect(), sprite(), color() Position and looks x, y and draw()
area() A collision shape Your AABB function
body(), setGravity(), jump(), isGrounded() Platformer physics Platformer 1
onCollide('tag', fn) React to overlaps Loops that test pairs
scene() / go() Game states The state variable
onUpdate, dt() Per-frame code, delta time update(dt)
tween(), wait(), loop() Timers and tweens Tweening
get('enemy') All objects with a tag objects.filter(...)

Note: With kaplay({ global: false }) nothing is added to the global scope; you call everything through the returned context instead: const k = kaplay({ global: false }); k.add([k.pos(0, 0)]). That is cleaner in bigger projects and with TypeScript.

Components and tags in plain JavaScript

The pattern itself is simple enough to write yourself. Each component is an object with data and optional hooks; add merges them into one game object:

js · try it yourself
const objects = [];

function add(parts) {
  const obj = { tags: new Set(), hooks: [] };
  for (const part of parts) {
    if (typeof part === 'string') { obj.tags.add(part); continue; }
    const { update, ...data } = part;
    Object.assign(obj, data);
    if (update) obj.hooks.push(update);
  }
  objects.push(obj);
  return obj;
}
const get = (tag) => objects.filter((o) => o.tags.has(tag) && !o.dead);

// components
const pos = (x, y) => ({ x, y });
const named = (name) => ({ name });
const health = (hp) => ({
  hp,
  hurt(n) {
    this.hp -= n;
    console.log(`${this.name} takes ${n}, hp ${this.hp}`);
    if (this.hp <= 0) { this.dead = true; console.log(`${this.name} is destroyed`); }
  },
});
const patrol = (speed) => ({ dir: 1, update(o, dt) { o.x += o.dir * speed * dt; if (o.x > 100 || o.x < 0) o.dir *= -1; } });

add([named('hero'), pos(10, 50), health(5), 'player']);
add([named('slime'), pos(40, 50), health(2), patrol(40), 'enemy']);
add([named('bat'), pos(90, 20), health(1), patrol(60), 'enemy', 'flying']);

for (let i = 0; i < 4; i++) for (const o of objects) for (const h of o.hooks) h(o, 0.25);
console.log('enemies:', get('enemy').map((e) => `${e.name}@${e.x}`).join(', '));
for (const e of get('enemy')) e.hurt(1);
console.log('still alive:', get('enemy').map((e) => e.name).join(', '));
console.log('flying:', get('flying').length);
enemies: slime@80, bat@60
slime takes 1, hp 1
bat takes 1, hp 0
bat is destroyed
still alive: slime
flying: 0

Composition makes new object types cheap: a flying, patrolling enemy with health is just a different list of parts. Kaplay adds many more components (sprites with animations, timers, state machines, opacity, offscreen culling) and a proper event system.

Playable: a Kaplay-style platformer in raw canvas

The same idea as the Kaplay code above, built on the play kit with a small add() and four components. Arrow keys move, Space or Up jumps; collect all coins for a new set.

html · try it yourself
<style>
  html, body { margin: 0; height: 100%; background: #0e1018; overflow: hidden; }
  canvas { display: block; margin: 0 auto; width: min(100vw, 177.78vh); height: auto; outline: none; touch-action: none; }
</style>
<canvas width="480" height="270"></canvas>
<script>
// ---- play kit: click to focus, keep game keys inside the frame, fixed-step loop ----
const cv = document.querySelector('canvas'), ctx = cv.getContext('2d');
const W = cv.width, H = cv.height;
const keys = new Set(), pressed = new Set();   // keys held now / pressed since the last update
let active = false, idleDrawn = false;
cv.tabIndex = 0;
cv.addEventListener('pointerdown', () => cv.focus());
cv.addEventListener('focus', () => { active = true; });
cv.addEventListener('blur', () => { active = false; idleDrawn = false; keys.clear(); pressed.clear(); });
addEventListener('keydown', (e) => {
  if (e.code.startsWith('Arrow') || e.code === 'Space') e.preventDefault(); // don't scroll the lesson
  if (!e.repeat) pressed.add(e.code);
  keys.add(e.code);
});
addEventListener('keyup', (e) => keys.delete(e.code));
function banner(title, sub = '') {
  ctx.save();
  ctx.fillStyle = 'rgba(0,0,0,0.6)'; ctx.fillRect(0, 0, W, H);
  ctx.fillStyle = '#fff'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
  ctx.font = 'bold 22px system-ui, sans-serif'; ctx.fillText(title, W / 2, H / 2 - 10);
  ctx.font = '14px system-ui, sans-serif'; ctx.fillText(sub, W / 2, H / 2 + 18);
  ctx.restore();
}
function run(update, draw, help = '') {
  const STEP = 1 / 60;
  let acc = 0, last = performance.now();
  requestAnimationFrame(function frame(now) {
    const dt = Math.min((now - last) / 1000, 0.1);
    last = now;
    if (active) {
      acc += dt;
      while (acc >= STEP) { update(STEP); pressed.clear(); acc -= STEP; }
      draw();
    } else if (!idleDrawn) {
      draw(); banner('Click to play', help); idleDrawn = true;
    }
    requestAnimationFrame(frame);
  });
}
// ---- end of play kit ----

const GRAVITY = 1400;
let objects = [], DT = 1 / 60, score = 0;
const handlers = [];
function add(parts) {
  const o = { tags: new Set(), comps: [] };
  for (const c of parts) {
    if (typeof c === 'string') { o.tags.add(c); continue; }
    o.comps.push(c);
    for (const [k, v] of Object.entries(c)) if (k !== 'update' && k !== 'draw') o[k] = v;
  }
  o.is = (tag) => o.tags.has(tag);
  objects.push(o);
  return o;
}
const destroy = (o) => { o.dead = true; };
const onCollide = (a, b, fn) => handlers.push({ a, b, fn });
const overlaps = (p, q) => p.x < q.x + q.w && p.x + p.w > q.x && p.y < q.y + q.h && p.y + p.h > q.y;

// components
const pos = (x, y) => ({ x, y });
const color = (c) => ({ color: c });
const rect = (w, h) => ({ w, h, draw(o) { ctx.fillStyle = o.color; ctx.fillRect(Math.round(o.x), Math.round(o.y), o.w, o.h); } });
const body = (opt = {}) => ({
  vy: 0, grounded: false, isStatic: !!opt.isStatic,
  jump(force) { this.vy = -force; this.grounded = false; },
  move(vx) {
    this.x += vx * DT;
    for (const s of objects) if (s.isStatic && overlaps(this, s)) this.x = vx > 0 ? s.x - this.w : s.x + s.w;
  },
  update(o, dt) {
    if (o.isStatic) return;
    o.vy += GRAVITY * dt;
    o.y += o.vy * dt;
    o.grounded = false;
    for (const s of objects) {
      if (!s.isStatic || !overlaps(o, s)) continue;
      if (o.vy > 0) { o.y = s.y - o.h; o.grounded = true; } else o.y = s.y + s.h;
      o.vy = 0;
    }
  },
});

// the level
const solid = (x, y, w, h) => add([pos(x, y), rect(w, h), color('#3c466e'), body({ isStatic: true })]);
solid(0, 250, 200, 20); solid(260, 250, 220, 20);
solid(150, 195, 90, 10); solid(300, 150, 100, 10); solid(60, 120, 80, 10);
const player = add([pos(40, 200), rect(14, 16), color('#ffb74d'), body(), 'player']);
function spawnCoins() {
  for (const [x, y] of [[90, 100], [190, 175], [345, 130], [440, 230], [230, 230]]) add([pos(x, y), rect(8, 8), color('#ffd54f'), 'coin']);
}
spawnCoins();
onCollide('player', 'coin', (p, coin) => { destroy(coin); score++; });

function update(dt) {
  DT = dt;
  if (keys.has('ArrowLeft')) player.move(-160);
  if (keys.has('ArrowRight')) player.move(160);
  if ((pressed.has('Space') || pressed.has('ArrowUp')) && player.grounded) player.jump(520);
  for (const o of objects) for (const c of o.comps) c.update?.(o, dt);
  for (const h of handlers)
    for (const a of objects) if (a.is(h.a) && !a.dead)
      for (const b of objects) if (b.is(h.b) && !b.dead && overlaps(a, b)) h.fn(a, b);
  objects = objects.filter((o) => !o.dead);
  if (!objects.some((o) => o.is('coin'))) spawnCoins();
  if (player.y > H + 50) { player.x = 40; player.y = 200; player.vy = 0; }   // fell into the gap
}

function draw() {
  ctx.fillStyle = '#0e1018';
  ctx.fillRect(0, 0, W, H);
  for (const o of objects) for (const c of o.comps) c.draw?.(o);
  ctx.fillStyle = '#fff';
  ctx.font = '14px monospace';
  ctx.textAlign = 'left';
  ctx.textBaseline = 'top';
  ctx.fillText(`Score: ${score}`, 8, 8);
}

run(update, draw, 'Arrows move, Space/Up jumps');
</script>

Tip: Kaplay's playground (play.kaplayjs.com) runs examples in the browser, much like this course. Try porting one of this course's games to Kaplay: it is the quickest way to see what the library does for you, and what it hides.

Test yourself

In Kaplay, how do you give an object gravity and let it land on platforms?

  1. Extend a Body class
  2. Add the body() component (plus area()), and give platforms body({ isStatic: true })
  3. Call gravity(obj) every frame
  4. Set obj.physics = true

What is a tag such as 'coin' used for?

  1. Choosing the colour
  2. Grouping objects for queries and collision events, e.g. onCollide('coin', ...) and get('coin')
  3. Naming the file
  4. Setting the draw order only

Which library is Kaplay the continuation of?

  1. Phaser
  2. PixiJS
  3. Kaboom.js
  4. Three.js