0

How do you vertically align text in canvas, based on the font size assigned? For instance, I have a rectangle with the height of 100px, and the variable textSize. My goal is to always vertically center the text inside of this specific rectangle.

Link to JS Fiddle

HTML

<canvas id="canvas" width="500" height="100"></canvas>

JS

var textSize = 40;

function init() {

    canvas = document.getElementById("canvas");
    ctx = canvas.getContext("2d");

    ctx.beginPath();
    ctx.lineTo(0, 100);
    ctx.lineTo(0, 0);
    ctx.lineTo(500, 0);
    ctx.lineTo(500, 100);
    ctx.closePath();
    ctx.fillStyle = "#000";
    ctx.fill();
    ctx.closePath();

    // Text
    ctx.save();
    ctx.font = textSize + "px 'Oswald'";
    ctx.fillStyle = "#fff";
    ctx.textBaseline="middle";
    ctx.fillText("Hello, World", 100, (100 - textSize)/2);
    ctx.restore();
}

window.onload = init();
DRB
  • 633
  • 11
  • 24

2 Answers2

1

This answer might help

The canvas's context has a measureText function which you can use.

Community
  • 1
  • 1
Beep
  • 122
  • 4
  • Yes, this looks like the right answer. Especially considering different typefaces. – DRB Mar 02 '16 at 12:43
  • http://stackoverflow.com/questions/1134586/how-can-you-find-the-height-of-text-on-an-html-canvas – Kaiido Mar 02 '16 at 13:36
  • @Beep. While your link is helpful, please do not post link-only answers -- even when the links are to Stackoverflow itself. Instead, post your link as a comment to the original question and not as an answer. This helps us avoid duplicate Q&A on Stackoverflow. :-) – markE Mar 03 '16 at 19:15
0

When you are using textBaseline= "middle" Why you are calculating the y coordinate considering textSize? Probably

ctx.fillText("Hello, World", 100, 50);

This will do the job for you.

Mahesh
  • 1,427
  • 2
  • 19
  • 42
  • I'm looking for a calculation that works if the `textSize` variable changes. Perhaps aligning to top or bottom would make things easier, though? – DRB Mar 02 '16 at 12:33