87 lines
2.2 KiB
JavaScript
87 lines
2.2 KiB
JavaScript
|
export default class TextLine
|
||
|
{
|
||
|
constructor(text)
|
||
|
{
|
||
|
this.LEFT = 0;
|
||
|
this.CENTER = 1;
|
||
|
this.RIGHT = 2;
|
||
|
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;
|
||
|
this.alignment = this.LEFT;
|
||
|
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) {
|
||
|
case this.LEFT:
|
||
|
break;
|
||
|
case this.CENTER:
|
||
|
x -= this.estimatedTextWidth * 0.5;
|
||
|
break;
|
||
|
case this.RIGHT:
|
||
|
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);
|
||
|
}
|
||
|
}
|
||
|
}
|