import TextLine from "./TextLine.js"; export default class TextBox { constructor(text, width, context) { this.text = text; this.width = width; this.colorText = 'red'; this.colorShadow = 'black'; this.colorBorder = 'black'; this.hasShadow = false; this.hasBorder = false; this.font = 'Silkscreen'; this.textSize = 32; this.alignment = 0; this.verticalAlignment = 'top'; 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) { let milliseconds = 0; for (let l = 0; l < this.lines.length; l++) { this.lines[l].chars = 0; setTimeout( () => { this.lines[l].animate(msForChar); }, milliseconds ); milliseconds += this.lines[l].text.length * msForChar; } } draw(context, x, y) { if (this.verticalAlignment === 'bottom') { 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; } }