8000 Fix font.render text alignment (#100) · GameJs/gamejs@9210944 · GitHub
[go: up one dir, main page]

Skip to content

Commit 9210944

Browse files
authored
Fix font.render text alignment (#100)
improve font.render Provide generally viable default settings to be used when determining how much padding is to be used, but also expose optional parameters to give the user precise control when necessary.
1 parent f09bf3e commit 9210944

File tree

1 file changed

+8
-5
lines changed

1 file changed

+8
-5
lines changed

src/gamejs/font.js

+8-5
Original file line numberDiff line numberDiff line change
@@ -38,11 +38,15 @@ var Font = exports.Font = function(fontSettings, backgroundColor) {
3838
/**
3939
* Returns a Surface with the given text on it.
4040
* @param {String} text the text to render
41-
* @param {String} color a valid #RGB String, "#ffcc00"
41+
* @param {String=} color a valid #RGB String, "#ffcc00"
42+
* @param {String=} textBaseline a valid textBaseline value, "alphabetic|top|hanging|middle|ideographic|bottom"
43+
* @param {Number=} padding number of pixels of padding space to contain the text in.
4244
* @returns {gamejs.Surface} Surface with the rendered text on it.
4345
*/
44-
Font.prototype.render = function(text, color) {
46+
Font.prototype.render = function(text, color, textBaseline, padding) {
4547
var dims = this.size(text);
48+
var padding = padding || Math.ceil(dims[1] * 0.2);
49+
dims[1] += padding;
4650
var surface = new Surface(dims);
4751
var ctx = surface.context;
4852
ctx.save();
@@ -51,14 +55,13 @@ Font.prototype.render = function(text, color) {
5155
ctx.fillRect(0, 0, surface.rect.width, surface.rect.height);
5256
}
5357
ctx.font = this.sampleSurface.context.font;
54-
ctx.textBaseline = this.sampleSurface.context.textBaseline;
58+
ctx.textBaseline = textBaseline || 'alphabetic';
5559
ctx.textAlign = this.sampleSurface.context.textAlign;
5660
ctx.fillStyle = ctx.strokeStyle = color || "#000000";
57-
ctx.fillText(text, 0, surface.rect.height, surface.rect.width);
61+
ctx.fillText(text, 0, surface.rect.height - padding, surface.rect.width);
5862
ctx.restore();
5963
return surface;
6064
};
61-
6265
/**
6366
* Determine the width and height of the given text if rendered
6467
* with this Font.

0 commit comments

Comments
 (0)
0