Center (proportional font) text in an HTML5 canvas

后端 未结 5 1293
别那么骄傲
别那么骄傲 2020-12-18 19:41

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

5条回答
  •  無奈伤痛
    2020-12-18 20:13

    developer.mozilla.org states in the textAlign description that the alignment is based on the x value of the context's fillText() method. That is, the property does not center the text in the canvas horizontally; it centers the text around the given x coordinate. Similar applies for the textBaseLine.

    So in order to center the text in both directions, we need to set those two properties and position the text in the middle of the canvas.

    ctx.textBaseline = 'middle'; 
    ctx.textAlign = 'center'; 
    
    ctx.fillText('Game over', canvas_width/2, canvas_height/2);
    

提交回复
热议问题