LittleJS Documentation

repository·main·Indexed 26 days ago

https://github.com/killedbyapixel/littlejs

A high-performance, lightweight HTML5 game engine designed for simplicity and speed. LittleJS provides a comprehensive suite of features including hybrid 2D/3D rendering, arcade physics with Box2D integration, ZzFX audio, and input handling for mouse, keyboard, gamepad, and touch. It is suitable for complex games and size-constrained coding competitions, offering a Vite starter template for modern development and a variety of build files including ESM and minified versions.

Tokens
21.5K
Snippets
57
Records
116
Agent score
86%

What's inside LittleJS

  1. Overview of LittleJS features

    main

    LittleJS is a fast, lightweight HTML5 game engine with the following core capabilities:

    • Graphics: WebGL2 + Canvas2D hybrid rendering, Shadertoy-style shaders, particle systems, and support for TexturePacker/Aseprite atlases. Optional 3D rendering via a Three.js plugin.
    • Audio: Support for mp3, ogg, and wave files, spatial audio stereo panning, and ZzFX sound generation.
    • Input: Handling for mouse, keyboard, gamepad, and touch, including a customizable mobile on-screen gamepad.
    • Physics: Arcade physics with collision handling, tilemap collision, raycasting, and full Box2D integration (via Box2D v2.3.1 wasm). Includes an A* pathfinding plugin.
    • Developer Tools: Live example browser, Tiled JSON level import, debug overlays, and a Node.js build system.
  2. Use Vite with LittleJS

    main

    Use the official Vite starter template for a bundler-based setup with hot reload. Note that LittleJS uses global state, so the template performs a full page reload on save instead of partial HMR.

    To start a new project:

    npx degit KilledByAPixel/LittleJS/examples/vite-starter my-game
    cd my-game
    npm install
    npm run dev
  3. Use LittleJS with TypeScript

    main

    LittleJS includes type definitions in dist/littlejs.d.ts. When installed via npm, these are wired up automatically for type checking.

    import { engineInit, drawText, vec2 } from 'littlejsengine';
    
    function gameInit(): void {}
    function gameUpdate(): void {}
    function gameUpdatePost(): void {}
    function gameRender(): void {}
    function gameRenderPost(): void {
        drawText('Hello!', vec2(0,0), 4);
    }
    
    engineInit(gameInit, gameUpdate, gameUpdatePost, gameRender, gameRenderPost, ['tiles.png']);
  4. Load and add images to your game

    main

    To load images, pass an array of file paths as the final argument to engineInit. The engine ensures all images are loaded before starting the game loop. You can access the underlying image data via textureInfos[index].image.

    engineInit(gameInit, gameUpdate, gameUpdatePost, gameRender, gameRenderPost, ['tiles.png']);
  5. Handle assets in LittleJS + Vite

    main

    There are two ways to handle assets in this setup:

    1. Static Assets (Public Folder)

    Files placed in the public/ directory are served from the site root during development and copied directly to dist/ during build. This is useful for files passed directly to engineInit.

    Example: engineInit(..., ['tiles.png']) works if tiles.png is in public/.

    2. Bundled Assets (Importing)

    For assets you want Vite to process, hash, and bundle (recommended for large projects), import them directly from your src/ directory.

    import tilesURL from './tiles.png';
  6. Setup LittleJS Box2D Physics

    main

    LittleJS provides an optional plugin for the Box2D physics engine via box2d.wasm.js. To use it, you must initialize the WASM module before calling engineInit. You can toggle debug rendering and set world gravity using the global box2d object.

    // Setup (call once before engineInit)
    await box2dInit()              // Loads the WASM and creates global box2d / Box2dPlugin
    box2dSetDebug(true)            // Toggle debug rendering of physics shapes (box2dDebug)
    box2d.setGravity(vec2(0,-20))  // World gravity
  7. Debug your game with the LittleJS debug overlay

    main

    LittleJS includes a built-in debug overlay to help visualize game state.

    • Toggle Overlay: Press Esc to show/hide the overlay. It provides a list of available toggles and their corresponding number-key bindings.
    • Time Scaling: Use the + and - keys to adjust the time scale, allowing you to slow down or speed up the game simulation.
  8. Build and publish LittleJS games

    main

    Plain script-tag projects

    For production, use the release builds to strip asserts and reduce file size:

    • dist/littlejs.release.js: Stripped asserts.
    • dist/littlejs.min.js: Minified release.

    Vite / module projects

    Run npm run build and deploy the contents of the dist/ folder.

    Deployment Tips

    • GitHub Pages: Use relative asset paths (the Vite starter sets base: './') and include an empty .nojekyll file in your output.
    • itch.io: Zip your build output and upload as an HTML5 game. Enable "This file will be played in the browser" in settings.
    <!-- For production: stripped asserts, smaller -->
    <script src=dist/littlejs.release.js></script>
    
    <!-- Smallest: minified release -->
    <script src=dist/littlejs.min.js></script>
  9. Integrate Box2D with Vite

    main

    Box2D requires box2d.wasm.js (loader) and box2d.wasm.wasm (binary) to be served side-by-side. Because the loader uses document.currentScript.src to find the WASM file, it must be loaded as a classic <script> tag, not a module.

    1. Copy box2d.wasm.js and box2d.wasm.wasm from node_modules/littlejsengine/dist/ to your public/ folder.
    2. In index.html, add the script tag before your module script: <script src=./box2d.wasm.js></script>
    3. Await box2dInit() in your entry point before calling engineInit().

    To automate file copying, add this to your package.json:

    "scripts": {
      "postinstall": "node -e \"['box2d.wasm.js','box2d.wasm.wasm'].forEach(f=>require('fs').copyFileSync('node_modules/littlejsengine/dist/'+f,'public/'+f))\""
    }
    import { box2dInit, engineInit } from 'littlejsengine';
    
    await box2dInit();
    engineInit(gameInit, gameUpdate, gameUpdatePost, gameRender, gameRenderPost, ['tiles.png']);
  10. Use LittleJS as an ES module

    main

    If using a bundler (Vite, Rollup, webpack) or native ES modules, install via npm and import specific functions or the entire namespace.

    npm install littlejsengine
    import { engineInit, drawText, vec2 } from 'littlejsengine';
    
    function gameInit() {}
    function gameUpdate() {}
    function gameUpdatePost() {}
    function gameRender() {}
    function gameRenderPost() {
        drawText('Hello!', vec2(0,0), 4);
    }
    
    engineInit(gameInit, gameUpdate, gameUpdatePost, gameRender, gameRenderPost, ['tiles.png']);
  11. Deploy LittleJS + Vite projects

    main

    The template is pre-configured for easy deployment to platforms like GitHub Pages or itch.io. The vite.config.js uses base: './', ensuring the site works from any subdirectory.

    Deployment Steps:

    1. Build the project: npm run build.
    2. Upload the contents of the dist/ folder to your hosting provider (or zip the contents for itch.io).
    npm run build