Search code examples
javascriptjqueryhtmlcanvasfonts

Center (proportional font) text in an HTML5 canvas


I would like to be able to center single lines of text within rectangular areas I can calculate. The one thing I have expected to do in 2D geometry on a canvas is to center something whose width is unknown to you.

I have heard as a workaround that you can create the text in an HTML container and then call jQuery's width() function, but I ?didn't correctly handle the momentary addition to the document's body? and got a width of 0.

If I have a single line of text, significantly shorter than would fill most of the width in a screen, how can I tell how wide it will be on a canvas at a font size I know?


Solution

  • If you don't necessarily need a width of the text but just want to center text you can do

    canvas_context.textBaseline = "middle";
    canvas_context.textAlign = "center";
    

    Which should put a text centered both vertically and horizontally.

    See MDN's textAlign and textBaseline for extra info with pictures