Options
All
  • Public
  • Public/Protected
  • All
Menu

Class Label

Labels are the way to draw small amounts of text to the screen. They are actors and inherit all of the benefits and capabilities.

Creating a Label

You can pass in arguments to the Label.constructor or simply set the properties you need after creating an instance of the Label. Since labels are Actors, they need to be added to a Scene to be drawn and updated on-screen.

var game = new ex.Engine();
// constructor
var label = new ex.Label('Hello World', 50, 50, '10px Arial');
// properties
var label = new ex.Label();
label.pos.x = 50;
label.pos.y = 50;
label.fontFamily = 'Arial';
label.fontSize = 10;
label.fontUnit = ex.FontUnit.Px; // pixels are the default
label.text = 'Foo';
label.color = ex.Color.White;
label.textAlign = ex.TextAlign.Center;
// add to current scene
game.add(label);
// start game
game.start();

Adjusting Fonts

You can use the fontFamily, fontSize, fontUnit, textAlign, and baseAlign properties to customize how the label is drawn.

You can also use getTextWidth to retrieve the measured width of the rendered text for helping in calculations.

Web Fonts

The HTML5 Canvas API draws text using CSS syntax. Because of this, web fonts are fully supported. To draw a web font, follow the same procedure you use for CSS. Then simply pass in the font string to the Label constructor or set Label.fontFamily.

index.html

<!doctype html>
<html>
<head>
  <!-- Include the web font per usual -->
  <script src="//google.com/fonts/foobar"></script>
</head>
<body>
  <canvas id="game"></canvas>
  <script src="game.js"></script>
</body>
</html>

game.js

var game = new ex.Engine();
var label = new ex.Label();
label.fontFamily = 'Foobar, Arial, Sans-Serif';
label.fontSize = 10;
label.fontUnit = ex.FontUnit.Em;
label.text = 'Hello World';
game.add(label);
game.start();

Performance Implications

It is recommended to use a SpriteFont for labels as the raw Canvas API for drawing text is slow (fillText). Too many labels that do not use sprite fonts will visibly affect the frame rate of your game.

Alternatively, you can always use HTML and CSS to draw UI elements, but currently Excalibur does not provide a way to easily interact with the DOM. Still, this will not affect canvas performance and is a way to lighten your game, if needed.

Hierarchy

  • LabelImpl
    • Label

Implements

Index

Constructors

constructor

Properties

actionQueue

actionQueue: ActionQueue

Direct access to the actor's ActionQueue. Useful if you are building custom actions.

actions

actions: ActionContext

Action context of the actor. Useful for scripting actor behavior.

active

active: boolean = true

Whether this entity is active, if set to false it will be reclaimed

anchor

anchor: Vector

The anchor to apply all actor related transformations like rotation, translation, and scaling. By default the anchor is in the center of the actor. By default it is set to the center of the actor (.5, .5)

An anchor of (.5, .5) will ensure that drawings are centered.

Use anchor.setTo to set the anchor to a different point using values between 0 and 1. For example, anchoring to the top-left would be Actor.anchor.setTo(0, 0) and top-right would be Actor.anchor.setTo(0, 1).

baseAlign

baseAlign: BaseAlign = BaseAlign.Bottom

Gets or sets the baseline alignment property for the label.

bold

bold: boolean = false

Sets or gets the bold property of the label's text, by default it's false

caseInsensitive

caseInsensitive: boolean = true

Whether or not the SpriteFont will be case-sensitive when matching characters.

changes

changes: Observable<AddedComponent | RemovedComponent> = new Observable<AddedComponent | RemovedComponent>()

children

children: Actor[] = []

The children of this actor

components

components: ComponentMapper<KnownComponents> = new Proxy<ComponentMapper<KnownComponents>>({} as any, this._handleChanges)

currentDrawing

currentDrawing: Drawable = null

Access to the current drawing for the actor, this can be an Animation, Sprite, or Polygon. Set drawings with setDrawing.

enableCapturePointer

enableCapturePointer: boolean = false

Whether or not to enable the CapturePointer trait that propagates pointer events to this actor

eventDispatcher

eventDispatcher: EventDispatcher

Direct access to the game object event dispatcher.

fontFamily

fontFamily: string

The CSS font family string (e.g. sans-serif, Droid Sans Pro). Web fonts are supported, same as in CSS.

fontSize

fontSize: number = 10

The font size in the selected units, default is 10 (default units is pixel)

fontStyle

fontStyle: FontStyle = FontStyle.Normal

The font style for this label, the default is FontStyle.Normal

fontUnit

fontUnit: FontUnit = FontUnit.Px

The css units for a font size such as px, pt, em (SpriteFont only support px), by default is 'px';

frames

frames: object

Type declaration

id

id: number = ActorImpl.maxId++

The unique identifier for the actor

isOffScreen

isOffScreen: boolean = false

Indicates whether the actor is physically in the viewport

letterSpacing

letterSpacing: number = 0

Gets or sets the letter spacing on a Label. Only supported with Sprite Fonts.

logger

logger: Logger = Logger.getInstance()

Convenience reference to the global logger

maxWidth

maxWidth: number

Gets or sets the maximum width (in pixels) that the label should occupy

opacity

opacity: number = 1

The opacity of an actor. Passing in a color in the constructor will use the color's opacity.

parent

parent: Actor = null

The parent of this actor

previousOpacity

previousOpacity: number = 1

scene

scene: Scene = null

The scene that the actor is in

spriteFont

spriteFont: SpriteFont

The SpriteFont to use, if any. Overrides fontFamily if present.

text

text: string

The text to draw.

textAlign

textAlign: TextAlign = TextAlign.Left

Gets or sets the horizontal text alignment property for the label.

traits

traits: Trait[] = []

Modify the current actor update pipeline.

visible

visible: boolean = true

The visibility of an actor

Static maxId

maxId: number = 0

Indicates the next id to be set

Accessors

Protected _fontString

  • get _fontString(): string

acc

  • Gets the acceleration vector of the actor in pixels/second/second. An acceleration pointing down such as (0, 100) may be useful to simulate a gravitational effect.

    Returns Vector

  • Sets the acceleration vector of teh actor in pixels/second/second

    Parameters

    Returns void

body

  • get body(): Body
  • set body(body: Body): void
  • The physics body the is associated with this actor. The body is the container for all physical properties, like position, velocity, acceleration, mass, inertia, etc.

    Returns Body

  • The physics body the is associated with this actor. The body is the container for all physical properties, like position, velocity, acceleration, mass, inertia, etc.

    Parameters

    Returns void

center

color

  • Sets the color of the actor. A rectangle of this color will be drawn if no Drawable is specified as the actors drawing.

    The default is null which prevents a rectangle from being drawn.

    Returns Color

  • Sets the color of the actor. A rectangle of this color will be drawn if no Drawable is specified as the actors drawing.

    The default is null which prevents a rectangle from being drawn.

    Parameters

    Returns void

draggable

  • get draggable(): boolean
  • set draggable(isDraggable: boolean): void

height

  • get height(): number
  • set height(height: number): void

isInitialized

  • get isInitialized(): boolean

oldAcc

  • Gets the acceleration of the actor from the last frame. This does not include the global acc Physics.acc.

    Returns Vector

  • Sets the acceleration of the actor from the last frame. This does not include the global acc Physics.acc.

    Parameters

    Returns void

oldPos

  • Gets the position vector of the actor from the last frame

    Returns Vector

  • Sets the position vector of the actor in the last frame

    Parameters

    Returns void

oldScale

  • Gets the old scale of the actor last frame

    obsolete

    ex.Actor.scale will be removed in v0.25.0, set width and height directly in constructor

    Returns Vector

  • Sets the the old scale of the actor last frame

    obsolete

    ex.Actor.scale will be removed in v0.25.0, set width and height directly in constructor

    Parameters

    Returns void

oldVel

  • Gets the velocity vector of the actor from the last frame

    Returns Vector

  • Sets the velocity vector of the actor from the last frame

    Parameters

    Returns void

pos

rotation

  • get rotation(): number
  • set rotation(theAngle: number): void
  • Gets the rotation of the actor in radians. 1 radian = 180/PI Degrees.

    Returns number

  • Sets the rotation of the actor in radians. 1 radian = 180/PI Degrees.

    Parameters

    • theAngle: number

    Returns void

rx

  • get rx(): number
  • set rx(angularVelocity: number): void
  • Gets the rotational velocity of the actor in radians/second

    Returns number

  • Sets the rotational velocity of the actor in radians/sec

    Parameters

    • angularVelocity: number

    Returns void

scale

  • Gets the scale vector of the actor

    obsolete

    ex.Actor.scale will be removed in v0.25.0, set width and height directly in constructor

    Returns Vector

  • Sets the scale vector of the actor for

    obsolete

    ex.Actor.scale will be removed in v0.25.0, set width and height directly in constructor

    Parameters

    Returns void

sx

  • get sx(): number
  • set sx(scalePerSecondX: number): void
  • Gets the x scalar velocity of the actor in scale/second

    obsolete

    ex.Actor.sx will be removed in v0.25.0, set width and height directly in constructor

    Returns number

  • Sets the x scalar velocity of the actor in scale/second

    obsolete

    ex.Actor.sx will be removed in v0.25.0, set width and height directly in constructor

    Parameters

    • scalePerSecondX: number

    Returns void

sy

  • get sy(): number
  • set sy(scalePerSecondY: number): void
  • Gets the y scalar velocity of the actor in scale/second

    obsolete

    ex.Actor.sy will be removed in v0.25.0, set width and height directly in constructor

    Returns number

  • Sets the y scale velocity of the actor in scale/second

    obsolete

    ex.Actor.sy will be removed in v0.25.0, set width and height directly in constructor

    Parameters

    • scalePerSecondY: number

    Returns void

types

  • get types(): string[]

vel

width

  • get width(): number
  • set width(width: number): void

z

  • get z(): number
  • set z(newZ: number): void

Methods

_initialize

  • _initialize(engine: Engine): void
  • Initializes this actor and all it's child actors, meant to be called by the Scene before first update not by users of Excalibur.

    It is not recommended that internal excalibur methods be overridden, do so at your own risk.

    internal

    Parameters

    Returns void

_postdraw

  • _postdraw(ctx: CanvasRenderingContext2D, delta: number): void
  • It is not recommended that internal excalibur methods be overridden, do so at your own risk.

    Internal _postdraw handler for onPostDraw lifecycle event

    internal

    Parameters

    • ctx: CanvasRenderingContext2D
    • delta: number

    Returns void

_postkill

  • _postkill(_scene: Scene): void
  • It is not recommended that internal excalibur methods be overridden, do so at your own risk.

    Internal _prekill handler for onPostKill lifecycle event

    internal

    Parameters

    Returns void

_postupdate

  • _postupdate(engine: Engine, delta: number): void
  • It is not recommended that internal excalibur methods be overridden, do so at your own risk.

    Internal _preupdate handler for onPostUpdate lifecycle event

    internal

    Parameters

    • engine: Engine
    • delta: number

    Returns void

_predraw

  • _predraw(ctx: CanvasRenderingContext2D, delta: number): void
  • It is not recommended that internal excalibur methods be overridden, do so at your own risk.

    Internal _predraw handler for onPreDraw lifecycle event

    internal

    Parameters

    • ctx: CanvasRenderingContext2D
    • delta: number

    Returns void

_prekill

  • _prekill(_scene: Scene): void
  • It is not recommended that internal excalibur methods be overridden, do so at your own risk.

    Internal _prekill handler for onPreKill lifecycle event

    internal

    Parameters

    Returns void

_preupdate

  • _preupdate(engine: Engine, delta: number): void
  • It is not recommended that internal excalibur methods be overridden, do so at your own risk.

    Internal _preupdate handler for onPreUpdate lifecycle event

    internal

    Parameters

    • engine: Engine
    • delta: number

    Returns void

add

  • add(actor: Actor): void
  • Adds a child actor to this actor. All movement of the child actor will be relative to the parent actor. Meaning if the parent moves the child will move with it.

    Parameters

    • actor: Actor

      The child actor to add

    Returns void

addComponent

  • addComponent<T>(componentOrEntity: T | Entity<T>, force?: boolean): Entity<never | T>

addDrawing

  • addDrawing(texture: Texture): void
  • addDrawing(sprite: Sprite): void
  • addDrawing(key: any, drawing: Drawable): void

clearTextShadow

  • clearTextShadow(): void
  • Clears the current text shadow

    Returns void

clone

contains

  • contains(x: number, y: number, recurse?: boolean): boolean
  • Tests whether the x/y specified are contained in the actor

    Parameters

    • x: number

      X coordinate to test (in world coordinates)

    • y: number

      Y coordinate to test (in world coordinates)

    • Default value recurse: boolean = false

      checks whether the x/y are contained in any child actors (if they exist).

    Returns boolean

debugDraw

  • debugDraw(ctx: CanvasRenderingContext2D): void

draw

  • draw(ctx: CanvasRenderingContext2D, delta: number): void

emit

  • emit(eventName: string, eventObject: GameEvent<any>): void

getAncestors

  • getAncestors(): Actor[]

getGlobalScale

getTextWidth

  • getTextWidth(ctx: CanvasRenderingContext2D): number
  • Returns the width of the text in the label (in pixels);

    Parameters

    • ctx: CanvasRenderingContext2D

      Rendering context to measure the string with

    Returns number

getWorldPos

  • Gets an actor's world position taking into account parent relationships, scaling, rotation, and translation

    Returns Vector

    Position in world coordinates

getWorldRotation

  • getWorldRotation(): number
  • Gets this actor's rotation taking into account any parent relationships

    Returns number

    Rotation angle in radians

getZIndex

  • getZIndex(): number
  • Gets the z-index of an actor. The z-index determines the relative order an actor is drawn in. Actors with a higher z-index are drawn on top of actors with a lower z-index

    Returns number

has

  • has(type: string): boolean

isKilled

  • isKilled(): boolean

kill

  • kill(): void
  • If the current actor is a member of the scene, this will remove it from the scene graph. It will no longer be drawn or updated.

    Returns void

off

  • off(eventName: Events.exittrigger, handler?: function): void
  • off(eventName: Events.entertrigger, handler?: function): void
  • off(eventName: Events.collisionstart, handler?: function): void
  • off(eventName: Events.collisionend, handler?: function): void
  • off(eventName: Events.precollision, handler?: function): void
  • off(eventName: Events.postcollision, handler: function): void
  • off(eventName: Events.pointerup, handler?: function): void
  • off(eventName: Events.pointerdown, handler?: function): void
  • off(eventName: Events.pointerenter, handler?: function): void
  • off(eventName: Events.pointerleave, handler?: function): void
  • off(eventName: Events.pointermove, handler?: function): void
  • off(eventName: Events.pointercancel, handler?: function): void
  • off(eventName: Events.pointerwheel, handler?: function): void
  • off(eventName: Events.pointerdragstart, handler?: function): void
  • off(eventName: Events.pointerdragend, handler?: function): void
  • off(eventName: Events.pointerdragenter, handler?: function): void
  • off(eventName: Events.pointerdragleave, handler?: function): void
  • off(eventName: Events.pointerdragmove, handler?: function): void
  • off(eventName: Events.prekill, handler?: function): void
  • off(eventName: Events.postkill, handler?: function): void
  • off(eventName: Events.initialize, handler?: function): void
  • off(eventName: Events.postupdate, handler?: function): void
  • off(eventName: Events.preupdate, handler?: function): void
  • off(eventName: Events.postdraw, handler?: function): void
  • off(eventName: Events.predraw, handler?: function): void
  • off(eventName: Events.enterviewport, handler?: function): void
  • off(eventName: Events.exitviewport, handler?: function): void
  • off(eventName: string, handler?: function): void

on

  • on(eventName: Events.exittrigger, handler: function): void
  • on(eventName: Events.entertrigger, handler: function): void
  • on(eventName: Events.collisionstart, handler: function): void
  • on(eventName: Events.collisionend, handler: function): void
  • on(eventName: Events.precollision, handler: function): void
  • on(eventName: Events.postcollision, handler: function): void
  • on(eventName: Events.kill, handler: function): void
  • on(eventName: Events.prekill, handler: function): void
  • on(eventName: Events.postkill, handler: function): void
  • on(eventName: Events.initialize, handler: function): void
  • on(eventName: Events.preupdate, handler: function): void
  • on(eventName: Events.postupdate, handler: function): void
  • on(eventName: Events.predraw, handler: function): void
  • on(eventName: Events.postdraw, handler: function): void
  • on(eventName: Events.predebugdraw, handler: function): void
  • on(eventName: Events.postdebugdraw, handler: function): void
  • on(eventName: Events.pointerup, handler: function): void
  • on(eventName: Events.pointerdown, handler: function): void
  • on(eventName: Events.pointerenter, handler: function): void
  • on(eventName: Events.pointerleave, handler: function): void
  • on(eventName: Events.pointermove, handler: function): void
  • on(eventName: Events.pointercancel, handler: function): void
  • on(eventName: Events.pointerwheel, handler: function): void
  • on(eventName: Events.pointerdragstart, handler: function): void
  • on(eventName: Events.pointerdragend, handler: function): void
  • on(eventName: Events.pointerdragenter, handler: function): void
  • on(eventName: Events.pointerdragleave, handler: function): void
  • on(eventName: Events.pointerdragmove, handler: function): void
  • on(eventName: Events.enterviewport, handler: function): void
  • on(eventName: Events.exitviewport, handler: function): void
  • on(eventName: string, handler: function): void

onInitialize

  • onInitialize(_engine: Engine): void
  • onInitialize is called before the first update of the actor. This method is meant to be overridden. This is where initialization of child actors should take place.

    Synonymous with the event handler .on('initialize', (evt) => {...})

    Parameters

    Returns void

onPostDraw

  • onPostDraw(_ctx: CanvasRenderingContext2D, _delta: number): void
  • Safe to override onPostDraw lifecycle event handler. Synonymous with .on('postdraw', (evt) =>{...})

    onPostDraw is called directly after an actor is drawn, and before local transforms are removed.

    Parameters

    • _ctx: CanvasRenderingContext2D
    • _delta: number

    Returns void

onPostKill

  • onPostKill(_scene: Scene): void
  • Safe to override onPostKill lifecycle event handler. Synonymous with .on('postkill', (evt) => {...})

    onPostKill is called directly after an actor is killed and remove from its current Scene.

    Parameters

    Returns void

onPostUpdate

  • onPostUpdate(_engine: Engine, _delta: number): void
  • Safe to override onPostUpdate lifecycle event handler. Synonymous with .on('postupdate', (evt) =>{...})

    onPostUpdate is called directly after an actor is updated.

    Parameters

    • _engine: Engine
    • _delta: number

    Returns void

onPreDraw

  • onPreDraw(_ctx: CanvasRenderingContext2D, _delta: number): void
  • Safe to override onPreDraw lifecycle event handler. Synonymous with .on('predraw', (evt) =>{...})

    onPreDraw is called directly before an actor is drawn, but after local transforms are made.

    Parameters

    • _ctx: CanvasRenderingContext2D
    • _delta: number

    Returns void

onPreKill

  • onPreKill(_scene: Scene): void
  • Safe to override onPreKill lifecycle event handler. Synonymous with .on('prekill', (evt) =>{...})

    onPreKill is called directly before an actor is killed and removed from its current Scene.

    Parameters

    Returns void

onPreUpdate

  • onPreUpdate(_engine: Engine, _delta: number): void
  • Safe to override onPreUpdate lifecycle event handler. Synonymous with .on('preupdate', (evt) =>{...})

    onPreUpdate is called directly before an actor is updated.

    Parameters

    • _engine: Engine
    • _delta: number

    Returns void

once

  • once(eventName: Events.exittrigger, handler: function): void
  • once(eventName: Events.entertrigger, handler: function): void
  • once(eventName: Events.collisionstart, handler: function): void
  • once(eventName: Events.collisionend, handler: function): void
  • once(eventName: Events.precollision, handler: function): void
  • once(eventName: Events.postcollision, handler: function): void
  • once(eventName: Events.kill, handler: function): void
  • once(eventName: Events.postkill, handler: function): void
  • once(eventName: Events.prekill, handler: function): void
  • once(eventName: Events.initialize, handler: function): void
  • once(eventName: Events.preupdate, handler: function): void
  • once(eventName: Events.postupdate, handler: function): void
  • once(eventName: Events.predraw, handler: function): void
  • once(eventName: Events.postdraw, handler: function): void
  • once(eventName: Events.predebugdraw, handler: function): void
  • once(eventName: Events.postdebugdraw, handler: function): void
  • once(eventName: Events.pointerup, handler: function): void
  • once(eventName: Events.pointerdown, handler: function): void
  • once(eventName: Events.pointerenter, handler: function): void
  • once(eventName: Events.pointerleave, handler: function): void
  • once(eventName: Events.pointermove, handler: function): void
  • once(eventName: Events.pointercancel, handler: function): void
  • once(eventName: Events.pointerwheel, handler: function): void
  • once(eventName: Events.pointerdragstart, handler: function): void
  • once(eventName: Events.pointerdragend, handler: function): void
  • once(eventName: Events.pointerdragenter, handler: function): void
  • once(eventName: Events.pointerdragleave, handler: function): void
  • once(eventName: Events.pointerdragmove, handler: function): void
  • once(eventName: Events.enterviewport, handler: function): void
  • once(eventName: Events.exitviewport, handler: function): void
  • once(eventName: string, handler: function): void

remove

  • remove(actor: Actor): void
  • Removes a child actor from this actor.

    Parameters

    • actor: Actor

      The child actor to remove

    Returns void

removeComponent

  • removeComponent<ComponentOrType>(componentOrType: ComponentOrType, force?: boolean): Entity<ExcludeType<never, ComponentOrType>>
  • Removes a component from the entity, by default removals are deferred to the end of entity processing to avoid consistency issues

    Components can be force removed with the force flag, the removal is not deferred and happens immediately

    Type parameters

    Parameters

    • componentOrType: ComponentOrType
    • Default value force: boolean = false

    Returns Entity<ExcludeType<never, ComponentOrType>>

setDrawing

  • setDrawing(key: string): void
  • setDrawing(key: number): void
  • Sets the current drawing of the actor to the drawing corresponding to the key.

    Parameters

    • key: string

      The key of the drawing

    Returns void

  • Sets the current drawing of the actor to the drawing corresponding to an enum key (e.g. Animations.Left)

    Parameters

    • key: number

      The enum key of the drawing

    Returns void

setTextShadow

  • setTextShadow(offsetX: number, offsetY: number, shadowColor: Color): void
  • Sets the text shadow for sprite fonts

    Parameters

    • offsetX: number

      The x offset in pixels to place the shadow

    • offsetY: number

      The y offset in pixels to place the shadow

    • shadowColor: Color

      The color of the text shadow

    Returns void

setZIndex

  • setZIndex(newIndex: number): void
  • Sets the z-index of an actor and updates it in the drawing list for the scene. The z-index determines the relative order an actor is drawn in. Actors with a higher z-index are drawn on top of actors with a lower z-index

    Parameters

    • newIndex: number

      new z-index to assign

    Returns void

unkill

  • unkill(): void
  • If the current actor is killed, it will now not be killed.

    Returns void

update

  • update(engine: Engine, delta: number): void

useTextShadow

  • useTextShadow(on: boolean): void
  • Toggles text shadows on or off, only applies when using sprite fonts

    Parameters

    • on: boolean

    Returns void

within

  • within(actor: Actor, distance: number): boolean
  • Returns true if the two actor.body.collider.shape's surfaces are less than or equal to the distance specified from each other

    Parameters

    • actor: Actor

      Actor to test

    • distance: number

      Distance in pixels to test

    Returns boolean

Object literals

capturePointer

capturePointer: object

Configuration for CapturePointer trait

captureDragEvents

captureDragEvents: false = false

captureMoveEvents

captureMoveEvents: false = false

Static defaults

defaults: object

Indicates the next id to be set

anchor

anchor: Vector = Vector.Half