js/Mobilizing/text/StyledTextElement.js
import StyledLetter from "./StyledLetter";
/**
* StyledTextElement is a simple class to organise text elements extacted from HTML text. It contains an array of StyledLetter.
*/
export default class StyledTextElement {
/**
* @param {Object} params Parameters object, given by the constructor.
* @param {String} params.text the text string (character)
* @param {Number} [params.size=40] the size of the font
* @param {Font} params.font a Mobilizing font reference
* @param {Color} [params.color="black"] a CSS Color
*/
constructor({
text = "",
font = undefined,
size = 40,
color = "black",
} = {}) {
this.text = text;
this.font = font;
this.size = size;
this.color = color;
this.line = 0;
this.x = 0;
this.y = 0;
this.width = 0;
this.height = 0;
this.styledLetters = [];
if (this.font) {
this.update();
}
}
/**
* Updates properties according to the new settings (including styledLetters array properties)
*/
update() {
const size = this.font.getTextSize(this.text, this.size);
this.width = size.width;
this.height = size.height;
this.path = this.font.getFont().getPath(this.text, this.x, this.y, this.size);
this.path.fill = this.color;
this.boundingBox = this.path.getBoundingBox();
let baseWidth = 0;
for (let i = 0; i < this.styledLetters.length; i++) {
const styledLetter = this.styledLetters[i];
styledLetter.font = this.font;
if (i === 0) {
styledLetter.setX(this.x);
baseWidth = styledLetter.width;
}
else {
styledLetter.setX(this.x + baseWidth);
baseWidth += styledLetter.width;
}
styledLetter.setY(this.y);
styledLetter.setSize(this.size);
styledLetter.setColor(this.color);
styledLetter.update();
}
}
/**
* Defines the letter's font
* @param {Font} font
*/
setFont(font) {
this.font = font;
}
/**
* Defines the letter's color
* @param {Color} color
*/
setColor(color) {
this.color = color;
}
/**
* Defines the letter's x
* @param {Number} x
*/
setX(x) {
this.x = x;
}
/**
* Defines the letter's y
* @param {Number} y
*/
setY(y) {
this.y = y;
}
/**
* Defines the letter's font size
* @param {Font} size
*/
setSize(size) {
this.size = size;
}
/**
* Defines the letter's path
* @param {Path} path openType.js object's Path
*/
setPath(path) {
this.path = path;
}
/**
* Defines the letter's text string
* @param {String} text
*/
setText(text) {
this.text = text;
this.styledLetters = [];
for (let i = 0; i < this.text.length; i++) {
const char = this.text.charCodeAt(i);
const styledLetter = new StyledLetter({
letter: String.fromCharCode(char),
font: this.font,
size: this.size,
color: this.color
});
this.styledLetters.push(styledLetter);
}
}
}