Game Development Reference
In-Depth Information
How do you calculate the size of text? There isn't really an easy way to do this in HTML. This code
uses a simple trick: you dynamically add the text to the HTML page, calculate its size when it's
drawn, and remove it again. Here is the function that does this work for you:
function calculateTextSize(fontname, fontsize, text) {
var div = document.createElement("div");
div.style.position = "absolute";
div.style.left = -1000;
div.style.top = -1000;
document.body.appendChild(div);
text = typeof text !== 'undefined' ? text : "M";
div.style.fontSize = "" + fontsize;
div.style.fontFamily = fontname;
div.innerHTML = text;
var size = new Vector2(div.offsetWidth, div.offsetHeight);
document.body.removeChild(div);
return size;
}
You first create a
div
element, in which you place the text. You set the position of the element to
(-1000, 1000) so that it's drawn outside of the screen. You place the text and calculate its size, which
you then store in a
Vector2
object. This object is returned as a result of this function. Although this
isn't a very neat way of solving the problem, it's very easy to do and works fine. When you program,
sometimes these quick and dirty hacks are acceptable, but be careful not to use them all the time. In
this case, you have no choice because there is no alternative way to do this in HTML.
In the
Label
class, you calculate the size of the text when the text content is set. This is done in the
text
property:
Object.defineProperty(Label.prototype, "text",
{
get: function () {
return this._contents;
},
set: function (value) {
this._contents = value;
this._size = calculateTextSize(this._fontname, this._fontsize,
value);
}
});
The
Label
class also needs a
draw
method in order to draw the text on the screen. Drawing text on
the screen is done by calling the
Canvas2D.drawText
method. You use the
world position
of the text
label when drawing the text, so that text-based game objects can also be part of the hierarchy. Here
is the complete
draw
method:
Label.prototype.draw = function () {
if (!this.visible)
return;
Canvas2D.drawText(this._contents, this.worldPosition, this.origin,
this.color, this._align, this._fontname, this._fontsize);
};
Search WWH ::
Custom Search