The codeleap for this section may be accessed here. In this section, we will discuss Labels and their attributes. Following this explanation, we will implement a label.
Subsections
01 A Word on Labels
02 Adding a Label to the Scene
03 Adding a Listener to the Label
We can add text to the screen using a class Enchant.js provides called Labels. Labels are a simple way to add text to scenes, and we can use them to represent things like score, player health, and other metrics. Let’s talk about some key attributes of the Label class.
The x and y attributes allow us to set the location of a label. Remember that the y-axis is flipped in this context, so the position y = 0 is actually at the top of the scene and as y increases, a label will move down.
The color attribute allows us to set the color of a label. A label may be assigned colors according to the format of the CSS ‘color’ property.
i.e.) SOME_LABEL.color = “red”; to set a label’s color to red
The font attribute allows us to set the font of a label. This may be used to set the font type, font size, font weight, and more according to the format of the CSS ‘font’ property.
i.e) SOME_LABEL.font = "32px monospace"; to set a label’s size to 32 pixels and monospace
The textAlign attribute allows us to set the alignment of a label. A label may be assigned an alignment according to the format of the CSS ‘text-align’ property.
i.e.) SOME_LABEL.textAlign = “center”; to set a label’s alignment to center
You can read more about these CSS properties here:
color
font
text-align
The text attribute allows us to set the text of a label. This is the actual text that appears on screen. This can be concatenated with other variables by using ‘+’.
i.e.) SOME_LABEL.text = “Score: “ + SOME_VAR; to set a label’s text to “Score: “ concatenated with the value of SOME_VAR
Now that we understand Labels a little more, let’s try adding a label to the scene. This should be as simple as instantiating a Label object and giving it the desired text as a parameter.
Let’s implement a Label in our example code. (Once again, you can access it from here.)
"Score: 0"
. Under 05.2 Create a Label add:
scoreLabel = new Label("Score: 0");
game.rootScene.addChild(scoreLabel);
Having text on the screen is nice, but let’s make it so that the label’s text changes based on some variable that changes. We’ll accomplish this by adding an enterframe
event listener to the label.
scoreLabel.addEventListener('enterframe', function(){
this.text = "Score: "+game.score;
});