2020-02-24 21:09:21 +01:00
|
|
|
import TextAlignment from "./TextAlignment.js";
|
|
|
|
|
2020-02-24 00:19:21 +01:00
|
|
|
export default class TextLine
|
|
|
|
{
|
|
|
|
constructor(text)
|
|
|
|
{
|
|
|
|
this.text = text;
|
|
|
|
this.estimatedTextWidth = null;
|
|
|
|
this.colorText = 'red';
|
|
|
|
this.colorShadow = 'black';
|
|
|
|
this.colorBorder = 'black';
|
|
|
|
this.font = 'sans-serif';
|
|
|
|
this.alphaText = 1.0;
|
|
|
|
this.size = 32;
|
2020-02-24 21:09:21 +01:00
|
|
|
this.alignment = TextAlignment.LEFT;
|
2020-02-24 00:19:21 +01:00
|
|
|
this.chars = this.text.length;
|
|
|
|
this.hasShadow = false;
|
|
|
|
this.hasBorder = false;
|
|
|
|
}
|
|
|
|
|
|
|
|
animate(msPerChar = 100)
|
|
|
|
{
|
|
|
|
this.chars = 0;
|
|
|
|
|
|
|
|
let process = setInterval(
|
|
|
|
() => {
|
|
|
|
this.chars++;
|
|
|
|
|
|
|
|
if (this.chars === this.text.length) {
|
|
|
|
clearInterval(process);
|
|
|
|
}
|
|
|
|
}, msPerChar
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
draw(context, x, y)
|
|
|
|
{
|
|
|
|
context.font = this.size + 'px ' + this.font;
|
|
|
|
context.globalAlpha = this.alphaText;
|
|
|
|
|
|
|
|
if (this.estimatedTextWidth === null) {
|
|
|
|
this.estimatedTextWidth = Math.ceil(context.measureText(this.text).width);
|
|
|
|
}
|
|
|
|
|
|
|
|
switch (this.alignment) {
|
2020-02-24 21:09:21 +01:00
|
|
|
case TextAlignment.LEFT:
|
2020-02-24 00:19:21 +01:00
|
|
|
break;
|
2020-02-24 21:09:21 +01:00
|
|
|
case TextAlignment.CENTER:
|
2020-02-24 00:19:21 +01:00
|
|
|
x -= this.estimatedTextWidth * 0.5;
|
|
|
|
break;
|
2020-02-24 21:09:21 +01:00
|
|
|
case TextAlignment.RIGHT:
|
2020-02-24 00:19:21 +01:00
|
|
|
x -= this.estimatedTextWidth;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
|
|
|
this.drawShadow(context, x, y);
|
|
|
|
|
|
|
|
let text = this.text;
|
|
|
|
|
|
|
|
if (this.chars !== null && this.chars < this.text.length) {
|
|
|
|
text = this.text.substr(0, this.chars);
|
|
|
|
}
|
|
|
|
|
|
|
|
context.fillStyle = this.colorText;
|
|
|
|
context.fillText(text, x, y + this.size);
|
|
|
|
|
|
|
|
this.drawBorder(context, x, y, text);
|
|
|
|
}
|
|
|
|
|
|
|
|
drawBorder(context, x, y, text)
|
|
|
|
{
|
|
|
|
if (this.hasBorder) {
|
|
|
|
context.strokeStyle = this.colorBorder;
|
|
|
|
context.strokeWidth = '1px';
|
|
|
|
context.strokeText(text, x, y + this.size);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
drawShadow(context, x, y)
|
|
|
|
{
|
|
|
|
if (this.hasShadow) {
|
|
|
|
context.fillStyle = this.colorShadow;
|
|
|
|
context.fillText(this.text.substr(0, this.chars), x + 2, y + this.size + 2);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|