Game Development Reference
In-Depth Information
We also added a powerOfTwo function to calculate the width of canvas:
SpriteTexture.prototype.powerOfTwo=function(textWidth, width) {
var width = width || 1;
while(width<textWidth) {
width *= 2;
}
return width;
}
This function is important as most WebGL implementations require that the texture
dimensions must be in the power of two. Now if the width of our text becomes 150,
then our canvas size has to be 256. If the width is 100, then the width of the canvas
has to be 128. The width of the canvas is equal to the size of texture. This function
sets the width to 1 and multiplies it by 2 until the width is greater than the passed
textWidth variable.
The complete drawing happens in the createTexture function, which is defined
as follows:
SpriteTexture.prototype.createTexture=function(textData){
var text=[];
var width=0;
var canvasX=0;
var canvasY=0;
//Sets the font size
this.ctx.font=this.textSize +"px Georgia";
If the text width is greater than the value of maxWidth , then we invoke the
createMultilineText function to store the split text in the text array; otherwise,
we store the string in the text array. Basically, the text array stores the string
lines to be rendered. For the multiline text, we use the width returned by the
createMultilineText function, otherwise we use the width of the passed string
using the canvas API's measureText function. We pass the calculated width to the
powerOfTwo function to calculate the appropriate width. The following code snippet
explains the working of the the createTexture function:
// If the text width is greater than maxWidth, then call
multiline, else, store the string in text array.
if (this.maxWidth&this.measureText(textData) >this.maxWidth ) {
width = this.createMultilineText(textData,text);
canvasX = this.powerOfTwo(width);
} else {
text.push(textData);
canvasX = this.powerOfTwo(this.ctx.measureText(textData).width);
}
 
Search WWH ::




Custom Search