Center text in HTML Canvas

In order to center text in an HTML canvas vertically and horizontally, you have to do the following:

  1. Make sure you are working on the context by using the getContext("2d") method.

  2. set the “textBaseline” to “middle” so that the text gets centered vertically

  3. Set the “textAlign” to “center” so that the text gets centered horizontally

  4. In the “fillText” method, set the x coordinate to half of the canvas width and set the y coordinate to half of the canvas height.

Check out at the following example or check out the codepen where I center the text in the HTML canvas.

Example:

HTML:

 <canvas id="canvas" width="300" height="300" style="border:1px solid #000000;">

Javascript:

let canvas = document.getElementById('canvas');

let canvasContext = canvas.getContext("2d");

//Center vertically
canvasContext.textBaseline = 'middle'; 

//Center Horizontally
canvasContext.textAlign = 'center'; 

//Set the x cordinate to half of the Canvas width, set the y cordinate to half of the Canvas height
canvasContext.fillText("hi kids", canvas.width/2, canvas.height/2);

The result will look like this

Screenshot of centered text in HTML canvas