craftyjs.github.com

Text

Events

Change
when the text is changed

Component to make a text entity.

By default, text will have the style "10px sans-serif".

Note 1: An entity with the text component is just text! If you want to write text inside an image, you need one entity for the text and another entity for the image. More tips for writing text inside an image: (1) Use the z-index (from 2D component) to ensure that the text is on top of the image, not the other way around; (2) use .attach() (from 2D component) to glue the text to the image so they move and rotate together.

Note 2: For DOM (but not canvas) text entities, various font settings (like text-decoration and text-align) can be set using .css() (see DOM component). But you cannot use .css() to set the properties which are controlled by .textFont() or .textColor() -- the settings will be ignored.

Back to top

.text

public this .text(String text)

public this .text(Function textgenerator)

text
String of text that will be inserted into the DOM or Canvas element.

This method will update the text inside the entity.

If you need to reference attributes on the entity itself you can pass a function instead of a string.

Example

Crafty.e("2D, DOM, Text").attr({ x: 100, y: 100 }).text("Look at me!!");

Crafty.e("2D, DOM, Text").attr({ x: 100, y: 100 })
    .text(function () { return "My position is " + this._x });

Crafty.e("2D, Canvas, Text").attr({ x: 100, y: 100 }).text("Look at me!!");

Crafty.e("2D, Canvas, Text").attr({ x: 100, y: 100 })
    .text(function () { return "My position is " + this._x });
Back to top

.textColor

public this .textColor(String color, Number strength)

color
The color in hexadecimal
strength
Level of opacity

Modify the text color and level of opacity.

Example

Crafty.e("2D, DOM, Text").attr({ x: 100, y: 100 }).text("Look at me!!")
  .textColor('#FF0000');

Crafty.e("2D, Canvas, Text").attr({ x: 100, y: 100 }).text('Look at me!!')
  .textColor('#FF0000', 0.6);

See Also

Back to top

.textFont

public this .textFont(String key, * value)

key
Property of the entity to modify
value
Value to set the property to

public this .textFont(Object map)

map
Object where the key is the property to modify and the value as the property value

Use this method to set font property of the text entity.

Example

Crafty.e("2D, DOM, Text").textFont({ type: 'italic', family: 'Arial' });
Crafty.e("2D, Canvas, Text").textFont({ size: '20px', weight: 'bold' });

Crafty.e("2D, Canvas, Text").textFont("type", "italic");
Crafty.e("2D, Canvas, Text").textFont("type"); // italic
Back to top

.unselectable

public this .unselectable()

This method sets the text so that it cannot be selected (highlighted) by dragging. (Canvas text can never be highlighted, so this only matters for DOM text.) Works by changing the css property "user-select" and its variants.

Example

Crafty.e("2D, DOM, Text").text('This text cannot be highlighted!').unselectable();