Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Font rendering not centered in source surface #99

Open
arcman7 opened this issue Jul 28, 2020 · 1 comment
Open

Font rendering not centered in source surface #99

arcman7 opened this issue Jul 28, 2020 · 1 comment

Comments

@arcman7
Copy link
Contributor

arcman7 commented Jul 28, 2020

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.

@oberhamsi
Copy link
Member

thanks, if you make a PR i will take a look.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants