Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/OmarMtya/enginejs-module/llms.txt

Use this file to discover all available pages before exploring further.

Environment is the central static class of Engine.js. It owns every piece of shared state the engine needs to run: the canvas context, the live list of figures, physics constants, the animation backup, and the click-listener hook. Because all members are static, there is never an instance of Environment — you interact with it directly on the class, or through the $g global that index.js attaches to window. See also: Motor API for the animation-loop functions that consume this state, and Concepts: Environment for a narrative introduction.

Static Properties

The properties below are defined directly on the Environment class. Assign to them before calling $g.Animar to configure the engine.
canvas
CanvasRenderingContext2D
The 2D rendering context obtained from the HTML canvas element. Set automatically by InitCanvas and InitCanvasStatic. All draw calls in the Motor pipeline operate on this context.
canvasHTML
HTMLCanvasElement
A reference to the raw DOM <canvas> element. Used by detectarClick to attach and detach the onclick handler. Set by InitCanvas; not set by InitCanvasStatic.
container
HTMLElement
The container element whose dimensions drive dynamic canvas sizing. Set by InitCanvas. Not used by InitCanvasStatic.
FPS
number
default:"60"
Frames per second used as a divisor in physics calculations (gravity acceleration). Changing this value before starting the animation loop scales how quickly gravity accumulates per frame.
altura
number
default:"800"
Canvas height in pixels. Updated by InitCanvas (derived from container.offsetHeight - 4) or set directly by InitCanvasStatic. The physics engine uses this value as the floor boundary.
anchura
number
default:"800"
Canvas width in pixels. Updated by InitCanvas (derived from container.offsetWidth) or set directly by InitCanvasStatic.
gravedad
number
default:"9.8"
Gravity constant applied to every Rigido-enabled figure per frame. This value is also used as the reset value for a figure’s rigido.valor after a collision transfer. Adjust it before calling $g.Animar to change the global gravity of your scene.
figuras
Figura[]
default:"[]"
The live registry of all figures currently in the scene. Every call to AgregarFigura pushes into this array. The Motor iterates this array on every frame to draw and advance physics. See Concepts: Figures.
contador
number
default:"0"
An integer that increments by 1 on every call to Dibujar. Use it as a cheap frame counter for time-based game logic that does not require a high-resolution timestamp.
audioGeneral
undefined
Declared as a static property (static audioGeneral;) but never assigned by the engine. Its value is undefined at runtime unless your own code writes to it. Reserved for a future global audio controller.
backup
Figura[]
default:"[]"
A deep-cloned snapshot of Environment.figuras taken at the moment IniciarAnimacion is called. When DetenerAnimacion is invoked, the engine restores every figure from this snapshot so the scene returns to its exact initial state. See Guides: Animation Loop.
clickListener
function
default:"() => {}"
A callback invoked with the clicked Figura when click-detection is active. Replace it with your own handler before (or after) calling $g.DetectarClick(true):
$g.clickListener = function(figura) {
  console.log('Clicked:', figura.nombre);
};
$g.DetectarClick(true);
See Guides: Click Events.

Static Methods

InitCanvas

Initialises the canvas context using a container element to derive dynamic dimensions. This is the recommended initialisation path for responsive layouts.
$g.InitCanvas(canvas, container);
canvas
HTMLCanvasElement
required
The <canvas> DOM element to initialise. The method calls canvas.getContext("2d") internally and stores the result in Environment.canvas.
container
HTMLElement
required
A container element used to calculate the canvas dimensions dynamically. altura is set to container.offsetHeight - 4 and anchura to container.offsetWidth. The 4 px subtraction prevents scrollbar-induced overflow.
Returns: void Side effects:
  • Environment.canvascanvas.getContext("2d")
  • Environment.canvasHTMLcanvas
  • Environment.containercontainer
  • Environment.alturacontainer.offsetHeight - 4
  • Environment.anchuracontainer.offsetWidth
  • canvas.setAttribute('height', ...) and canvas.setAttribute('width', ...) are called to sync the DOM element’s actual pixel dimensions.
Call InitCanvas after the container element is rendered in the DOM so that offsetHeight and offsetWidth return correct values. Calling it before DOM paint will produce 0 × 0 canvas dimensions.
Example:
const canvas = document.getElementById('myCanvas');
const container = document.getElementById('gameContainer');
$g.InitCanvas(canvas, container);

InitCanvasStatic

Initialises the canvas context with fixed, hard-coded pixel dimensions. Use this when you want a fixed-size canvas independent of the viewport.
$g.InitCanvasStatic(canvas, anchura, altura);
canvas
HTMLCanvasElement
required
The <canvas> DOM element to initialise.
anchura
number
required
Fixed canvas width in pixels.
altura
number
required
Fixed canvas height in pixels.
Returns: void Side effects:
  • Environment.canvascanvas.getContext("2d")
  • Environment.anchuraanchura
  • Environment.alturaaltura
Unlike InitCanvas, this method does not set Environment.canvasHTML or Environment.container, and it does not call setAttribute on the element. If you need click detection ($g.DetectarClick), you must also set Environment.canvasHTML = canvas manually before enabling it.
Example:
const canvas = document.getElementById('myCanvas');
$g.InitCanvasStatic(canvas, 1024, 768);

AgregarFigura

Registers a Figura instance with the engine, adding it to the live Environment.figuras array so it will be drawn and simulated on every frame.
$g.AgregarFigura(figura);
figura
Figura
required
A Figura instance to add to the scene. Construct one with new $g.Figura({...}) before passing it here. See API: Figura.
Returns: void Side effects: Pushes figura onto Environment.figuras. Example:
const box = new $g.Figura({
  tipo: 'cuadrado',
  transform: new $g.Transform({ x: 100, y: 100, anchura: 50, altura: 50 })
});
$g.AgregarFigura(box);

Copy

Creates a deep clone of a Figura instance. Primitive properties (coordinates, dimensions, fill colour, etc.) are deep-copied via JSON.parse(JSON.stringify(...)). Media object references (transform.imagen and transform.sonido) are re-attached by reference rather than cloned, so all copies share the same loaded Image and Audio objects.
const clone = $g.Copy(figura);
obj
Figura
required
The Figura instance to clone.
Returns: Figura — a new Figura object whose transform and (optionally) rigido are independent copies of the originals. Cloning behaviour in detail:
PropertyClone strategy
id, nombre, tipoDeep-copied (primitive strings)
transform.x, y, anchura, altura, radio, rellenoDeep-copied
transform.imagenReference copied — same Imagen/HTMLImageElement object
transform.sonidoReference copied — same Sonido/HTMLAudioElement object
rigidoNew Rigido(valor, sinColision) — fresh physics state
Copy is called internally by both IniciarAnimacion (to build Environment.backup) and DetenerAnimacion (to restore figures from the backup). You can also call it yourself to duplicate figures at runtime.
Example:
const original = new $g.Figura({
  tipo: 'circulo',
  transform: new $g.Transform({ x: 200, y: 50, radio: 30, relleno: '#ff0000' }),
  rigido: new $g.Rigido()
});
$g.AgregarFigura(original);

const duplicate = $g.Copy(original);
duplicate.transform.x = 300;
$g.AgregarFigura(duplicate);

GenerarId

Generates a random, collision-resistant string identifier suitable for use as a Figura id.
const id = $g.GenerarId();
Returns: string — a string of the form '_' + Math.random().toString(36).substr(2, 9), for example '_k7x2mq9p1'.
Figura’s constructor calls GenerarId() automatically when no id is provided, so you rarely need to call this directly. It is exposed for cases where you need to generate identifiers outside of a Figura constructor (e.g. tagging game objects in your own data structures).
Example:
const id = $g.GenerarId();
console.log(id); // e.g. "_k7x2mq9p1"

The $g Global

index.js runs an immediately-invoked function that attaches every engine export onto the Environment class and then assigns window.$g = Environment. This means the entire Engine.js API is reachable through the single global $g — no imports are required in plain HTML projects.
// index.js (simplified)
Environment.Figura           = Figura;
Environment.Transform        = Transform;
Environment.Rigido           = Rigido;
Environment.Imagen           = Imagen;
Environment.Sprite           = Sprite;
Environment.Sonido           = Sonido;
Environment.Animar           = IniciarAnimacion;
Environment.DetenerAnimacion = DetenerAnimacion;
Environment.Dibujar          = Dibujar;
Environment.DetectarClick    = detectarClick;

window.$g = Environment;
After the script loads you can use the following names without any import statement:
$g memberTypeDocs
$g.InitCanvasmethodthis page
$g.InitCanvasStaticmethodthis page
$g.AgregarFiguramethodthis page
$g.Copymethodthis page
$g.GenerarIdmethodthis page
$g.Figuraclass constructorAPI: Figura
$g.Transformclass constructorAPI: Transform
$g.Rigidoclass constructorAPI: Rigido
$g.Imagenclass constructorAPI: Imagen
$g.Spriteclass constructorAPI: Sprite
$g.Sonidoclass constructorAPI: Sonido
$g.AnimarfunctionAPI: Motor → IniciarAnimacion
$g.DetenerAnimacionfunctionAPI: Motor → DetenerAnimacion
$g.DibujarfunctionAPI: Motor → Dibujar
$g.DetectarClickfunctionAPI: Motor → detectarClick
Because $g is Environment, you can read and write static properties through it too:
$g.gravedad = 15;      // stronger gravity
$g.figuras.length;     // how many figures are in the scene
$g.clickListener = fn; // set the click callback

Build docs developers (and LLMs) love