Game Development Reference
In-Depth Information
We calculate canvasY with the font size ( (i+1)*this.textSize ), multiplied by the length
of the text array plus one. We also add another 30 units, to add more length of the
power bar:
canvasY = this.powerOfTwo(this.textSize*(text.length+1)+30);
//+30 for power stats
Sometimes, we may require a square texture. In that case, we set the height or width
to the greater of the two:
if(this.sqaureTexture){
(canvasX>canvasY) ? canvasY = canvasX : canvasX = canvasY;
//For squaring the texture
}
this.canvas.width = canvasX;
this.canvas.height = canvasY;
We calculate the location of the text. Note that we set the x location of the text to the
half of the width of the canvas. This is because we set the text alignment to center
using the following code:
var textX = canvasX/2;
var textY = canvasY/2;
this.ctx.textAlign = "center";
// Sets the alignment of text, e.g. left, center, right
this.ctx.textBaseline = "middle";
We paint the background of the canvas using the ctx.fillRect API call:
this.ctx.fillStyle = this.backgroundColor;
this.ctx.fillRect(0, 0, this.ctx.canvas.width,
this.ctx.canvas.height);
We set the font color using the following code:
this.ctx.fillStyle = this.color; // Sets the text color, it can
take a hex value or rgba value (e.g. rgba(255,0,0,0.5))
We draw each line of the text by iterating over the text array and we calculate textY
for each string line using the following code:
this.ctx.font=this.textSize +"px Georgia";
var offset = (canvasY - this.textSize*(text.length+1)) * 0.5;
for(var i = 0; i<text.length; i++) {
if(text.length> 1) {
textY = (i+1)*this.textSize + offset;
}
this.ctx.fillText(text[i], textX, textY);
}
 
Search WWH ::




Custom Search