Extension to font rendering to allow letterSpacing

This commit is contained in:
Nathan Kunicki 2016-03-08 17:26:09 -06:00
parent 89c3595f94
commit 68e205216f
2 changed files with 44 additions and 3 deletions

View File

@ -1,6 +1,6 @@
{ {
"name": "momentumengine", "name": "momentumengine",
"version": "0.2.1", "version": "0.3.0",
"description": "An ES6 game and animation engine.", "description": "An ES6 game and animation engine.",
"main": "src/es6.js", "main": "src/es6.js",
"repository": { "repository": {

View File

@ -17,6 +17,7 @@ class Text extends Entity {
this.textAlign = "start"; this.textAlign = "start";
this.textBaseline = "alphabetic"; this.textBaseline = "alphabetic";
this.direction = "inherit"; this.direction = "inherit";
this.letterSpacing = 0;
} }
@ -30,6 +31,46 @@ class Text extends Entity {
} }
_renderText (text, x, y, letterSpacing, renderFunc) {
// Code modified from original by David Hong (sozonov): https://jsfiddle.net/sozonov/mg1jkz3q/
if (!text || typeof text !== "string" || text.length === 0) {
return false;
}
let characters = text.split(""),
index = 0,
current,
currentPosition = x,
align = 1;
if (this.textAlign === "right") {
characters = characters.reverse();
align = -1;
} else if (this.textAlign === "center") {
let totalWidth = 0;
for (let i = 0; i < characters.length; i++) {
totalWidth += (this._game.context.measureText(characters[i]).width + letterSpacing);
}
currentPosition = x - (totalWidth / 2);
}
while (index < text.length) {
current = characters[index++];
renderFunc(current, currentPosition, y);
currentPosition += (align * (this._game.context.measureText(current).width + letterSpacing));
}
}
render () { render () {
if (this._game) { if (this._game) {
@ -42,12 +83,12 @@ class Text extends Entity {
if (this.font.fill) { if (this.font.fill) {
this._game.context.fillStyle = this.font.fill; this._game.context.fillStyle = this.font.fill;
this._game.context.fillText(this.text, this.relativeLeft, this.relativeTop); this._renderText(this.text, this.relativeLeft, this.relativeTop, this.letterSpacing, this._game.context.fillText.bind(this._game.context));
} }
if (this.font.stroke) { if (this.font.stroke) {
this._game.context.strokeStyle = this.font.stroke; this._game.context.strokeStyle = this.font.stroke;
this._game.context.strokeText(this.text, this.relativeLeft, this.relativeTop); this._renderText(this.text, this.relativeLeft, this.relativeTop, this.letterSpacing, this._game.context.strokeText.bind(this._game.context));
} }
return true; return true;