Skip to content

Font rendering not centered in source surface #99

@arcman7

Description

@arcman7

Issue: Rendered font has the top portion of letters such as t, cut off.

This issue is prevalent with different fonts; monospace, Arial, etc. It doesn't matter what the font size is either. Based on what I can tell, the default value for textBaseline is "Bottom". This causes most of the misalignment with the text to the edge of the canvas rectangle surface.

Font.prototype.render = function(text, color) {
   var dims = this.size(text);
   var surface = new Surface(dims);
   var ctx = surface.context;
   ctx.save();
   if ( this.backgroundColor ) {
       ctx.fillStyle = this.backgroundColor;
       ctx.fillRect(0, 0, surface.rect.width, surface.rect.height);
   }
   ctx.font = this.sampleSurface.context.font;
   ctx.textBaseline = this.sampleSurface.context.textBaseline;
   ctx.textAlign = this.sampleSurface.context.textAlign;
   ctx.fillStyle = ctx.strokeStyle = color || "#000000";
   ctx.fillText(text, 0, surface.rect.height, surface.rect.width);
   ctx.restore();
   return surface;
};

There seems to be some small adjustment factor at play as well; which is why I wrote this method:

/*
* @param font - instance of class Font.
* @param color - valid css color.
* @param text - text string.
*/
function  _write_screen_helper(text, color, font) { //eslint-disable-line
   const dims = font.size(text) // [x, y]
    dims[1] += 4 // add 4 pixels of padding
    const surface = new window.gamejs.graphics.Surface(dims);
    const ctx = surface.context;
    ctx.save();
    ctx.font = font.sampleSurface.context.font;
    ctx.textBaseline = 'alphabetic';
    ctx.textAlign = font.sampleSurface.context.textAlign;
    ctx.fillStyle = (ctx.strokeStyle = color || "#000000"); //eslint-disable-line
    // force text to render in a rectange 4 pixels shorter than the full surface
    ctx.fillText(text, 0, surface.rect.height - 4, surface.rect.width);
    ctx.restore();
    return surface;
  }

If this seems useful I'll make a PR of it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions