-
-
Notifications
You must be signed in to change notification settings - Fork 657
Renderables
Overview — The base class for all visual objects in melonJS. It provides positioning, transforms, anchor point, opacity, and a draw() method you can override for custom rendering.
The Renderable class extends Rect and is the foundation for all display objects. It doesn't draw anything by default — you override draw(renderer) with your own rendering logic using the Rendering API.
import { Renderable } from "melonjs";
class MyRenderable extends Renderable {
constructor(x, y) {
super(x, y, 50, 50);
this.anchorPoint.set(0, 0);
}
update(dt) {
// return true to trigger a redraw
return false;
}
draw(renderer) {
renderer.setColor("#FF0000");
renderer.fillRect(0, 0, this.width, this.height);
}
}
// add to the game world
app.world.addChild(new MyRenderable(100, 100));Key properties:
-
pos— position (ObservableVector3dwith x, y, z) -
anchorPoint— origin point for transforms (default0.5, 0.5= center) -
alpha— opacity (0.0 to 1.0) -
floating— iftrue, rendered in screen coordinates (not affected by camera) -
alwaysUpdate— iftrue,update()is called even when off-screen -
parentApp— access theApplicationinstance from the container tree
Overview — Draws sprite images from single frames, spritesheets, or packed texture atlases. Supports animations, flipping, scaling, and rotation.
Sprite extends Renderable and handles image rendering with animation support:
import { Sprite } from "melonjs";
// simple static sprite
const ball = new Sprite(0, 0, { image: "ball" });
app.world.addChild(ball);For animated sprites using a spritesheet:
const runner = new Sprite(0, 0, {
image: "character",
framewidth: 64,
frameheight: 64,
});
runner.addAnimation("run", [0, 1, 2, 3, 4, 3, 2, 1]);
runner.addAnimation("idle", [0]);
runner.setCurrentAnimation("run");
app.world.addChild(runner);For sprites using a texture atlas:
import { TextureAtlas, loader } from "melonjs";
const atlas = new TextureAtlas(
loader.getJSON("sprites"),
loader.getImage("sprites"),
);
const player = new Sprite(0, 0, {
image: atlas,
region: "player_idle",
});Overview — Render text using system fonts (Text) or bitmap fonts (BitmapText).
Text uses the browser's font rendering:
import { Text } from "melonjs";
const label = new Text(100, 50, {
font: "Arial",
size: 24,
fillStyle: "#FFFFFF",
textAlign: "center",
text: "Score: 0",
});
app.world.addChild(label);BitmapText uses a pre-rendered bitmap font for consistent rendering across platforms (recommended for WebGL):
import { BitmapText } from "melonjs";
const score = new BitmapText(10, 10, {
font: "PressStart2P",
text: "00000",
});
app.world.addChild(score);