Copyright Derek O'Reilly, Dundalk Institute of Technology (DkIT), Dundalk, Co. Louth, Ireland.
Quite often, there will be some static text in a game. If we want to display static images, then we can use a gameObject that does not override the GameObject class's update() method. An example is shown here. The code for this example is shown below.
/* Author: Derek O Reilly, Dundalk Institute of Technology, Ireland. */ const STATIC_TEXT_CENTRE = -1; class StaticText extends GameObject { /* Each gameObject MUST have a constructor() and a render() method. */ /* If the object animates, then it must also have an updateState() method. */ constructor(text, x, y, font, fontSize, colour) { super(null); /* as this class extends from GameObject, you must always call super() */ /* These variables depend on the object */ this.text = text; this.x = x; this.y = y; this.font = font; this.fontSize = fontSize; this.colour = colour; ctx.font = this.fontSize + "px " + this.font; this.width = ctx.measureText(this.text).width; if (this.x === STATIC_TEXT_CENTRE) { this.x = (canvas.width - this.width) / 2; } } render() { ctx.fillStyle = this.colour; ctx.fillText(this.text, this.x, this.y); } }
STATIC_TEXT_CENTRE is used as a flag that will set the text to be horrizontally centred.
const STATIC_TEXT_CENTRE = -1;
In the constructor() method, we measure the width of the text using the highlighted code below:
constructor(text, x, y, font, fontSize, colour)
{
super(null); /* as this class extends from GameObject, you must always call super() */
/* These variables depend on the object */
this.text = text;
this.x = x;
this.y = y;
this.font = font;
this.fontSize = fontSize;
this.colour = colour;
ctx.font = this.fontSize + "px " + this.font;
this.width = ctx.measureText(this.text).width;
if (this.x === STATIC_TEXT_CENTRE)
{
this.x = (canvas.width - this.width) / 2;
}
}
If "this.x" has been set to be the value STATIC_TEXT_CENTRE, then we centre the text, as shown in the highlighted code below.
constructor(text, x, y, font, fontSize, colour)
{
super(null); /* as this class extends from GameObject, you must always call super() */
/* These variables depend on the object */
this.text = text;
this.x = x;
this.y = y;
this.font = font;
this.fontSize = fontSize;
this.colour = colour;
ctx.font = this.fontSize + "px " + this.font;
this.width = ctx.measureText(this.text).width;
if (this.x === STATIC_TEXT_CENTRE)
{
this.x = (canvas.width - this.width) / 2;
}
}
Copyright Derek O' Reilly, Dundalk Institute of Technology (DkIT), Dundalk, Co. Louth, Ireland.