melonJS
    Preparing search index...

    Class Application

    The Application class is the main entry point for creating a melonJS game. The constructor resolves the given settings, creates the game world and registers DOM event listeners (resize, orientation, scroll); you MUST then call (and await) init, which builds the renderer, appends the canvas to the parent element, and starts the game loop — without it the application has no renderer and displays nothing.

    The Application instance provides access to the core game systems:

    • renderer — the active Canvas, WebGL or (experimental) WebGPU renderer
    • world — the root container for all game objects
    • viewport — the default camera / viewport

    The app instance is automatically passed to Stage#onResetEvent and Stage#onDestroyEvent, and is accessible from any renderable via parentApp.

    // create a new melonJS Application
    const app = new Application(800, 600, {
    parent: "screen",
    scaleMethod: "flex-width",
    renderer: 2, // AUTO
    });

    // build the renderer (mandatory — only suspends for WebGPU)
    await app.init();

    // add objects to the world
    app.world.addChild(new Sprite(0, 0, { image: "player" }));

    // access the viewport
    app.viewport.follow(player, app.viewport.AXIS.BOTH);
    Index
    • Exit fullscreen mode for this application.

      Does nothing when the browser has no fullscreen support, or when the application is not fullscreen, so it is safe to call blind. Unlike Application#requestFullscreen it needs no user gesture: a page is always allowed to give fullscreen back.

      Note that the user can leave fullscreen without this being called, with Escape or the browser's own control, so a UI showing the current state should read Application#isFullscreen back rather than remember what it last asked for.

      Returns void

    • Trigger a fullscreen request for this application. Defaults to this application's parentElement (the container the canvas was appended into — see Application#getParentElement), so the canvas and any sibling HUD / overlay markup inside that container go fullscreen together. Must be called from a USER GESTURE, a click or a key press. Browsers refuse it otherwise: the returned promise rejects, this logs the rejection and nothing happens on screen. That is why the example below hangs the call off a key rather than calling it at startup, and why a game offering fullscreen puts it behind a button or a menu entry.

      Does nothing when the browser has no fullscreen support, or when the application is already fullscreen.

      Parameters

      • Optionalelement: Element

        optional element to fullscreen instead of this.parentElement

      Returns void

      import { event, input } from "melonjs";

      // F toggles fullscreen, from anywhere in the game
      input.bindKey(input.KEY.F, "fullscreen");
      event.on(event.KEYDOWN, (action, keyCode, edge) => {
      // `edge` only: a held key auto-repeats, and a repeat would toggle
      // straight back out of what it just turned on
      if (action !== "fullscreen" || !edge) {
      return;
      }
      if (app.isFullscreen()) {
      app.exitFullscreen();
      } else {
      app.requestFullscreen();
      }
      });
    • Create a new melonJS Application. Constructing the instance is only the first half of starting a game: you MUST then call (and await) init to build the renderer — an Application on which init() has not resolved has no renderer, no canvas, and cannot render anything.

      Parameters

      • width: number

        The width of the canvas viewport

      • height: number

        The height of the canvas viewport

      • options: Partial<ApplicationSettings> = {}

        The optional parameters for the application and default renderer

      Returns Application

      const app = new Application(1024, 768, {
      parent: "game-container",
      scale: "auto",
      scaleMethod: "fit",
      renderer: 2, // AUTO
      });
      await app.init();
    accumulator: number
    accumulatorMax: number
    accumulatorUpdateDelta: number
    frameCounter: number
    frameRate: number
    isAlwaysDirty: boolean
    isDirty: boolean
    isInitialized: boolean

    true when this app instance has been initialized

    false
    
    lastUpdate: number

    Last time the game update loop was executed.
    Use this value to implement frame prediction in drawing events, for creating smooth motion while running game update logic at a lower fps.

    lastUpdateDelta: number

    Measured wall-clock cost of the most recent logic step, in ms (performance.now() taken either side of the world/stage update).

    Used by the fixed-timestep loop to avoid a spiral of death: the accumulator drains by at least this much, so a scene too heavy to simulate in real time slows down instead of locking up.

    Only the last step of a frame is recorded, so a frame that ran several catch-up steps reports less than its total update cost. Renamed from updateAverageDelta in 20.0.0.

    20.0.0

    lastUpdateStart: number | null
    mergeGroup: boolean

    when true, all objects will be added under the root world container.
    When false, a me.Container object will be created for each corresponding groups

    true
    
    parentElement: HTMLElement

    the parent HTML element holding the main canvas of this application

    pauseOnBlur: boolean

    Specify whether to pause this app when losing focus

    true
    
    // keep the default game instance running even when losing focus
    app.pauseOnBlur = false;
    renderer: Renderer

    a reference to the active Canvas, WebGL or (experimental) WebGPU renderer

    resumeOnFocus: boolean

    Specify whether to unpause this app when gaining back focus

    true
    
    settings: ResolvedApplicationSettings

    the given settings used when creating this application

    stepSize: number
    stopOnBlur: boolean

    Specify whether to stop this app when losing focus

    false
    
    updateDelta: number

    Simulated time advanced by one logic step, in ms — what world.update() receives. Fixed at 1000 / world.fps unless timer.interpolation is on, in which case it follows the real frame delta.

    Not to be confused with Application#lastUpdateDelta, which is how long that step actually took to compute.

    viewport: Camera2d

    The "default" camera of the stage that is currently active.

    It MIRRORS the active stage, so it changes with every state.change(), and its concrete class is whatever that stage resolved to: an explicit cameras entry on the stage, then the stage's own cameraClass, then the application's cameraClass, then a shared Camera2d.

    Typed as the base class on purpose. A stage overrides the application, and built-in stages do: the loading screen pins a Camera2d whatever cameraClass the application was given. So there is no type this property could carry that a stage could not contradict, and a 3D application would be told it has a Camera3d here while the loader is up.

    A 3D game therefore has two sound options, and neither of them is a cast. OWN the camera, which is the better one, because the type is never lost in the first place:

    class GameStage extends Stage {
    readonly camera: Camera3d;

    constructor(app) {
    const camera = new Camera3d(0, 0, app.renderer.width, app.renderer.height);
    super({ cameras: [camera] });
    // kept with its real type; nothing downstream has to narrow
    this.camera = camera;
    }
    }
    // or narrow where you read it, which the language already verifies
    if (app.viewport instanceof Camera3d) {
    app.viewport.setBasis(right, up, forward);
    }
    world: World

    a reference to the game world,
    a world is a virtual environment containing all the game objects

    • get canvas(): HTMLCanvasElement

      The HTML canvas element associated with this application's renderer.

      Returns HTMLCanvasElement

      // access the canvas DOM element
      const canvas = app.canvas;
    • Destroy this application instance and release all associated resources. Removes the canvas from the DOM, destroys the world, and unregisters all event listeners.

      Terminal: a destroyed Application cannot be re-initialized — init() rejects afterwards (and an init() still in flight aborts). Construct a new Application to start again.

      Parameters

      • removeCanvas: boolean = true

        if true, the canvas element is removed from the DOM (default: true)

      Returns void

      // clean up when done
      app.destroy();
    • Freeze the current stage for a fixed duration, then automatically resume. Useful for hit-stop / hit-pause effects on impact.

      Convenience proxy for state.freeze; see that method's documentation for the full behaviour matrix (extend-not-stack semantics, interaction with manual state.pause() / state.resume(), automatic cancellation on window blur, etc.).

      Parameters

      • duration: number

        duration of the freeze in milliseconds

      • Optionalmusic: boolean = false

        also pause the current music track during the freeze

      Returns Promise<void>

      a Promise that resolves once the freeze ends (or is cancelled)

      // simple hit-stop on impact
      app.freeze(80);

      // chain VFX after the freeze
      await app.freeze(120);
      spawnImpactParticles();
    • Build the renderer and everything that depends on it — the canvas (appended to the parent element), the initial resize layout, and the console banner. Reads Application#settings, resolved by the constructor; it takes no arguments of its own.

      Calling and awaiting this is mandatory — it is the second half of every Application's start-up, not an optional step. It resolves synchronously for the Canvas and WebGL backends, which acquire their context without suspending — but WebGPU cannot, and an application whose init() has not resolved has no renderer.

      Returns Promise<void>

      resolves once the application is ready to use

      if it fails to instantiate the requested renderer (e.g. renderer: video.WEBGL on a device with no WebGL 2 support)

      const app = new Application(640, 480, { parent: "screen" });
      await app.init();
    • Fired when a level is fully loaded and all renderable instantiated.
      Additionally the level id will also be passed to the called function.

      Returns void

      // call myFunction () everytime a level is loaded
      app.onLevelLoaded = this.myFunction.bind(this);
    • Pause the current stage. Convenience proxy for state.pause.

      Parameters

      • Optionalmusic: boolean = false

        also pause the current music track

      Returns void

      app.pause();        // pause game updates, keep music playing
      app.pause(true); // pause game updates and music
    • Trigger a manual resize of the application canvas to fit the parent element. This is automatically called on window resize/orientation change, but can be called manually if the parent element size changes programmatically.

      Returns void

      // force a resize after changing the parent element dimensions
      app.resize();