mr-crocs-adventures/js/ui/TextBox.js

118 lines
3.1 KiB
JavaScript
Raw Normal View History

2020-02-24 00:19:21 +01:00
import TextLine from "./TextLine.js";
import TextAlignment from "./TextAlignment.js";
import UserInterfaceElement from "./UserInterfaceElement.js";
2020-02-24 00:19:21 +01:00
export default class TextBox extends UserInterfaceElement
2020-02-24 00:19:21 +01:00
{
constructor(text, width, context)
{
super();
2020-02-24 00:19:21 +01:00
this.text = text;
this.width = width;
this.colorText = 'red';
this.colorShadow = 'black';
this.colorBorder = 'black';
this.hasShadow = true;
this.hasBorder = true;
2020-02-24 00:19:21 +01:00
this.font = 'Silkscreen';
this.textSize = 48;
this.alignment = TextAlignment.CENTER;
this.verticalAlignment = TextAlignment.BOTTOM;
2020-02-24 00:19:21 +01:00
this.lines = [];
this.updateLines(width, context);
}
updateLines(width, context)
{
context.font = this.textSize + 'px ' + this.font;
this.lines = this.getLinesForWidth(this.text, context, width)
}
animate(msForChar = 100, timeoutMilliseconds = 0)
2020-02-24 00:19:21 +01:00
{
let milliseconds = 0;
setTimeout(
() => {
for (let l = 0; l < this.lines.length; l++) {
this.lines[l].chars = 0;
setTimeout(
() => {
this.lines[l].animate(msForChar);
}, milliseconds
);
2020-02-24 00:19:21 +01:00
milliseconds += this.lines[l].text.length * msForChar;
}
}, timeoutMilliseconds
);
2020-02-24 00:19:21 +01:00
}
draw(context, x = null, y = null)
2020-02-24 00:19:21 +01:00
{
if (x === null && y === null) {
x = this.position.x;
y = this.position.y;
}
if (this.verticalAlignment === TextAlignment.BOTTOM) {
2020-02-24 00:19:21 +01:00
let currentHeight = y;
for (let l = this.lines.length - 1; l >= 0; l--) {
if (this.lines[l].chars > 0) {
this.lines[l].draw(context, x, currentHeight);
currentHeight -= this.textSize;
}
}
return;
}
this.lines.forEach(
(line, index) => {
line.draw(context, x, y + this.textSize * index);
}
)
}
getLinesForWidth(text, context, width)
{
let words = text.split(' ');
let lines = [];
let buffer = words[0];
for (let w = 1; w < words.length; w++) {
let bufferNew = buffer === '' ? words[w] : buffer + ' ' + words[w];
if (context.measureText(bufferNew).width > width) {
lines.push(this.getLine(buffer));
bufferNew = words[w];
}
buffer = bufferNew;
}
if (buffer !== '') {
lines.push(this.getLine(buffer));
}
return lines;
}
getLine(text)
{
let line = new TextLine(text);
line.font = this.font;
line.size = this.textSize;
line.colorText = this.colorText;
line.colorShadow = this.colorShadow;
line.alignment = this.alignment;
line.hasShadow = this.hasShadow;
line.hasBorder = this.hasBorder;
line.colorBorder = this.colorBorder;
return line;
}
}