In order to center text in an HTML canvas vertically and horizontally, you have to do the following:
-
Make sure you are working on the context by using the
getContext("2d")
method. -
set the "textBaseline" to "middle" so that the text gets centered vertically
-
Set the "textAlign" to "center" so that the text gets centered horizontally
-
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