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.x = 50;
label.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.font]].

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

Implements

Index

Constructors

constructor

  • new Label(text?: string, x?: number, y?: number, fontFamily?: string, spriteFont?: SpriteFont): Label
  • Parameters

    • Optional text: string

      The text of the label

    • Optional x: number

      The x position of the label

    • Optional y: number

      The y position of the label

    • Optional fontFamily: string

      Use any valid CSS font string for the label's font. Web fonts are supported. Default is 10px sans-serif.

    • Optional spriteFont: SpriteFont

      Use an Excalibur sprite font for the label's font, if a SpriteFont is provided it will take precedence over a css font.

    Returns Label

Properties

Private _color

_color: Color = Color.Black.clone()

Private _shadowColor

_shadowColor: Color = Color.Black.clone()

Private _shadowColorDirty

_shadowColorDirty: boolean = false

Private _shadowOffsetX

_shadowOffsetX: number = 0

Private _shadowOffsetY

_shadowOffsetY: number = 0

Private _shadowSprites

_shadowSprites: object

Type declaration

Private _textShadowOn

_textShadowOn: boolean = false

Private _textSprites

_textSprites: object

Type declaration

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.

anchor

anchor: Vector

The anchor to apply all actor related transformations like rotation, translation, and rotation. 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.

body

body: Body = new Body(this)

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.

caseInsensitive

caseInsensitive: boolean = true

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

children

children: Actor[] = []

The children of this actor

collisionGroups

collisionGroups: string[] = []

collisionType

collisionType: CollisionType = CollisionType.PreventCollision

Gets or sets the current collision type of this actor. By default it is (CollisionType.PreventCollision).

color

color: Color

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

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

currentDrawing

currentDrawing: IDrawable = 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)

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 = Actor.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

scale

scale: Vector = new ex.Vector(1, 1)

The scale vector of the actor

scene

scene: Scene = null

The scene that the actor is in

spriteFont

spriteFont: SpriteFont

The SpriteFont to use, if any. Overrides [[font]] if present.

sx

sx: number = 0

The x scalar velocity of the actor in scale/second

sy

sy: number = 0

The y scalar velocity of the actor in scale/second

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: IActorTrait[] = []

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
  • Returns 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

collisionArea

  • Gets the collision area shape to use for collision possible options are [CircleArea|circles], [PolygonArea|polygons], and [EdgeArea|edges].

    Returns ICollisionArea

  • Gets the collision area shape to use for collision possible options are [CircleArea|circles], [PolygonArea|polygons], and [EdgeArea|edges].

    Parameters

    Returns void

friction

  • get friction(): number
  • set friction(theFriction: number): void
  • Gets the coefficient of friction on this actor, this can be thought of as how sticky or slippery an object is.

    Returns number

  • Sets the coefficient of friction of this actor, this can ve thought of as how stick or slippery an object is.

    Parameters

    • theFriction: number

    Returns void

mass

  • get mass(): number
  • set mass(theMass: number): void
  • Get the current mass of the actor, mass can be thought of as the resistance to acceleration.

    Returns number

  • Sets the mass of the actor, mass can be thought of as the resistance to acceleration.

    Parameters

    • theMass: number

    Returns void

moi

  • get moi(): number
  • set moi(theMoi: number): void
  • Gets the current moment of inertia, moi can be thought of as the resistance to rotation.

    Returns number

  • Sets the current moment of inertia, moi can be thought of as the resistance to rotation.

    Parameters

    • theMoi: number

    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

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

  • Gets the position vector of the actor in pixels

    Returns Vector

  • Sets the position vector of the actor in pixels

    Parameters

    Returns void

restitution

  • get restitution(): number
  • set restitution(theRestitution: number): void
  • Gets the coefficient of restitution of this actor, represents the amount of energy preserved after collision. Think of this as bounciness.

    Returns number

  • Sets the coefficient of restitution of this actor, represents the amount of energy preserved after collision. Think of this as bounciness.

    Parameters

    • theRestitution: number

    Returns void

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

torque

  • get torque(): number
  • set torque(theTorque: number): void
  • Gets the current torque applied to the actor. Torque can be thought of as rotational force

    Returns number

  • Sets the current torque applied to the actor. Torque can be thought of as rotational force

    Parameters

    • theTorque: number

    Returns void

vel

  • Gets the velocity vector of the actor in pixels/sec

    Returns Vector

  • Sets the velocity vector of the actor in pixels/sec

    Parameters

    Returns void

x

  • get x(): number
  • set x(theX: number): void
  • Gets the x position of the actor relative to it's parent (if any)

    Returns number

  • Sets the x position of the actor relative to it's parent (if any)

    Parameters

    • theX: number

    Returns void

y

  • get y(): number
  • set y(theY: number): void
  • Gets the y position of the actor relative to it's parent (if any)

    Returns number

  • Sets the y position of the actor relative to it's parent (if any)

    Parameters

    • theY: number

    Returns void

z

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

  • Parameters

    • newZ: number

    Returns void

Methods

Private _fontDraw

  • _fontDraw(ctx: CanvasRenderingContext2D, delta: number, sprites: object): void
  • Parameters

    • ctx: CanvasRenderingContext2D
    • delta: number
    • sprites: object

    Returns void

Private _lookupBaseAlign

  • _lookupBaseAlign(baseAlign: BaseAlign): string
  • Parameters

    Returns string

Private _lookupFontUnit

  • _lookupFontUnit(fontUnit: FontUnit): string
  • Parameters

    Returns string

Private _lookupTextAlign

  • _lookupTextAlign(textAlign: TextAlign): string
  • Parameters

    Returns string

Protected _reapplyEffects

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

addCollisionGroup

  • addCollisionGroup(name: string): void
  • Adds an actor to a collision group. Actors with no named collision groups are considered to be in every collision group.

    Once in a collision group(s) actors will only collide with other actors in that group.

    Parameters

    • name: string

      The name of the collision group

    Returns void

addDrawing

  • addDrawing(texture: Texture): any
  • addDrawing(sprite: Sprite): any
  • addDrawing(key: any, drawing: IDrawable): any
  • Adds a whole texture as the "default" drawing. Set a drawing using setDrawing.

    Parameters

    Returns any

  • Adds a whole sprite as the "default" drawing. Set a drawing using setDrawing.

    Parameters

    Returns any

  • Adds a drawing to the list of available drawings for an actor. Set a drawing using setDrawing.

    Parameters

    Returns any

clearTextShadow

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

    Returns void

collides

  • Test whether the actor has collided with another actor, returns the intersection vector on collision. Returns null when there is no collision;

    Parameters

    • actor: Actor

      The other actor to test

    Returns Vector

collidesWithSide

  • Test whether the actor has collided with another actor, returns the side of the current actor that collided.

    Parameters

    • actor: Actor

      The other actor to test

    Returns Side

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
  • Parameters

    • ctx: CanvasRenderingContext2D

    Returns void

draw

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

    • ctx: CanvasRenderingContext2D
    • delta: number

    Returns void

emit

  • emit(eventName: string, eventObject?: GameEvent): void
  • Emits a new event

    Parameters

    • eventName: string

      Name of the event to emit

    • Optional eventObject: GameEvent

      Data associated with this event

    Returns void

getBottom

  • getBottom(): number
  • Gets the bottom edge of the actor

    Returns number

getBounds

getCenter

  • Get the center point of an actor

    Returns Vector

getCollisionHandlers

  • getCollisionHandlers(): object

getGlobalScale

getHeight

  • getHeight(): number
  • Gets the calculated height of an actor, factoring in scale

    Returns number

getLeft

  • getLeft(): number
  • Gets the left edge of the actor

    Returns number

getRelativeBounds

getRight

  • getRight(): number
  • Gets the right edge of the actor

    Returns number

getSideFromIntersect

  • Returns the side of the collision based on the intersection

    Parameters

    • intersect: Vector

      The displacement vector returned by a collision

    Returns Side

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

getTop

  • getTop(): number
  • Gets the top edge of the actor

    Returns number

getWidth

  • getWidth(): number
  • Gets the calculated width of an actor, factoring in scale

    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

integrate

  • integrate(delta: number): void
  • Perform euler integration at the specified time step

    Parameters

    • delta: number

    Returns void

isKilled

  • isKilled(): boolean
  • Indicates wether the actor has been killed.

    Returns 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: string, handler?: function): void
  • Alias for removeEventListener. If only the eventName is specified it will remove all handlers registered for that specific event. If the eventName and the handler instance are specified only that handler will be removed.

    Parameters

    • eventName: string

      Name of the event to listen for

    • Optional handler: function

      Event handler for the thrown event

    Returns void

on

  • on(eventName: kill, handler: function): any
  • on(eventName: initialize, handler: function): any
  • on(eventName: preupdate, handler: function): any
  • on(eventName: postupdate, handler: function): any
  • on(eventName: predraw, handler: function): any
  • on(eventName: postdraw, handler: function): any
  • on(eventName: predebugdraw, handler: function): any
  • on(eventName: postdebugdraw, handler: function): any
  • on(eventName: pointerup, handler: function): any
  • on(eventName: pointerdown, handler: function): any
  • on(eventName: pointermove, handler: function): any
  • on(eventName: pointercancel, handler: function): any
  • on(eventName: string, handler: function): any
  • Parameters

    • eventName: kill
    • handler: function

    Returns any

  • Parameters

    Returns any

  • Parameters

    Returns any

  • Parameters

    Returns any

  • Parameters

    Returns any

  • Parameters

    Returns any

  • Parameters

    Returns any

  • Parameters

    Returns any

  • Parameters

    • eventName: pointerup
    • handler: function
        • (event?: PointerEvent): void
        • Parameters

          • Optional event: PointerEvent

          Returns void

    Returns any

  • Parameters

    • eventName: pointerdown
    • handler: function
        • (event?: PointerEvent): void
        • Parameters

          • Optional event: PointerEvent

          Returns void

    Returns any

  • Parameters

    • eventName: pointermove
    • handler: function
        • (event?: PointerEvent): void
        • Parameters

          • Optional event: PointerEvent

          Returns void

    Returns any

  • Parameters

    • eventName: pointercancel
    • handler: function
        • (event?: PointerEvent): void
        • Parameters

          • Optional event: PointerEvent

          Returns void

    Returns any

  • Parameters

    • eventName: string
    • handler: function

    Returns any

onCollidesWith

  • onCollidesWith(group: string, func: function): void
  • Register a handler to fire when this actor collides with another in a specified group

    Parameters

    • group: string

      The group name to listen for

    • func: function

      The callback to fire on collision with another actor from the group. The callback is passed the other actor.

        • Parameters

          Returns void

    Returns void

onInitialize

  • onInitialize(engine: Engine): void
  • This 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.

    Parameters

    Returns void

remove

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

    Parameters

    • actor: Actor

      The child actor to remove

    Returns void

removeCollidesWith

  • removeCollidesWith(group: string): void
  • Removes all collision handlers for this group on this actor

    Parameters

    • group: string

      Group to remove all handlers for on this actor.

    Returns void

removeCollisionGroup

  • removeCollisionGroup(name: string): void
  • Removes an actor from a collision group.

    Parameters

    • name: string

      The name of the collision group

    Returns void

setDrawing

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

    Parameters

    • key: string

      The key of the drawing

    Returns any

  • 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 any

setHeight

  • setHeight(height: any): void
  • Sets the height of an actor, factoring in the current scale

    Parameters

    • height: any

    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

setWidth

  • setWidth(width: any): void
  • Sets the width of an actor, factoring in the current scale

    Parameters

    • width: any

    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
  • Parameters

    • engine: Engine
    • delta: number

    Returns 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 actors 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

Static extend

  • extend(methods: any): any
  • You may wish to extend native Excalibur functionality in vanilla Javascript. Any method on a class inheriting Class may be extended to support additional functionality. In the example below we create a new type called MyActor.

    var MyActor = Actor.extend({
    
       constructor: function() {
          this.newprop = 'something';
          Actor.apply(this, arguments);
       },
    
       update: function(engine, delta) {
          // Implement custom update
          // Call super constructor update
          Actor.prototype.update.call(this, engine, delta);
    
          console.log("Something cool!");
       }
    });
    
    var myActor = new MyActor(100, 100, 100, 100, Color.Azure);
    

    In TypeScript, you only need to use the extends syntax, you do not need to use this method of extension.

    Parameters

    • methods: any

      A JSON object contain any methods/properties you want to extend

    Returns any

Object literals

capturePointer

capturePointer: object

Configuration for CapturePointer trait

captureMoveEvents

captureMoveEvents: boolean = false