Game Development Reference
In-Depth Information
It first gets the object of the canvas element and then gets the reference to its context
object. The default values of backgroundColor , color (text color), and powerColor
are defined in the constructor. Also, the maxWidth value of the sprite is defined, in
case the text is very long. The this.power variable holds the relative strength value
with maximum being 10 ( this.fullPower ).
Then, we define two functions, SpriteTexture.prototype.createMultilineText
and SpriteTexture.prototype.measureText . The measureText function is shown
in the following code snippet:
SpriteTexture.prototype.measureText=function(textToMeasure) {
return this.ctx.measureText(textToMeasure).width;
}
The measureText function is straightforward. It uses the ctx.measureText function
of the canvas 2D API to get the width of the text.
The createMultilineText function is shown in the following code snippet:
/*
text is an array that holds the split multiline text.
TextData holds the text data to be split.
*/
SpriteTexture.prototype.createMultilineText=function(textData,text
) {
textData = textData.replace("\n"," ");
var currentText = textData;
var newText;
var subWidth = 0;
var maxLineWidth = 0;
var wordArray = textData.split(" ");
var wordsInCurrent, wordArrayLength;
wordsInCurrent = wordArrayLength = wordArray.length;
while(this.measureText(currentText)
>this.maxWidth&&wordsInCurrent> 1) {
wordsInCurrent--;
var linebreak = false;
currentText = newText = "";
//currentText holds the string that fits in max width
//newText holds the string left.
// The loop iterates over the words to copy the words to
current text or new text
for(var i = 0; i<wordArrayLength; i++) {
if (i<wordsInCurrent) {
currentText += wordArray[i];
 
Search WWH ::




Custom Search